gets an error when everything is implemented correctly
"message": "Target [Illuminate\\Database\\Eloquent\\Model] is not instantiable while building [App\\Http\\Services\\TournamentService, App\\Http\\Repository\\Tournament\\TournamentRepository].",
MY CODE:
CONTROLLER:
public function getTournamentUserByType(TournamentService $tournamentService)
{
$tounaments = $tournamentService->getAll();
}
SERVICE:
class TournamentService implements TournamentServiceInterface
{
private TournamentRepositoryInterface $tournamentRepository;
public function __construct(TournamentRepositoryInterface $tournamentRepository)
{
$this->tournamentRepository = $tournamentRepository;
}
/**
* #return Collection
*/
public function getAll(): Collection
{
return $this->tournamentRepository->all();
}
REPOSITORY INTERFACE:
interface TournamentRepositoryInterface
{
/**
* #return Collection
*/
public function all(): Collection;
MY REPOSITORY:
class TournamentRepository extends BaseRepository implements TournamentRepositoryInterface
{
/**
* #param Model $model
*/
public function __construct(Model $model)
{
parent::__construct($model);
}
/**
* #return Collection
*/
public function all(): Collection
{
return $this->model->all();
}
Everything looks correct, I completely don't know why it gives me this error
I have trouble passing PHPStan tests because of parent/child classes (besides, code runs well).
These two kind of errors always show up:
Parameter #1 $a of method xxx expects ConcreteChildClass, AbstractParentClass given
Property ClassName::$a (ConcreteChildClass) does not accept AbstractParentClass
Here is the code (must be compatible with PHP 5.6):
<?php
abstract class AbstractClassA
{
/**
* #return static
*/
abstract public function postProcess();
}
class ConcreteClassA extends AbstractClassA
{
/**
* #return ConcreteClassA
*/
public function postProcess()
{
return $this;
}
}
abstract class AbstractClassB
{
/**
* #return AbstractClassA
*/
abstract public function deserialize();
/**
* #return AbstractClassA
*/
public function someMethodA($params)
{
return $this->someMethodB();
}
/**
* #return AbstractClassA
*/
public function someMethodB()
{
$object = $this->deserialize();
return $object->postProcess();
}
}
class ConcreteClassB extends AbstractClassB
{
/**
* #return ConcreteClassA
*/
public function deserialize()
{
$object = new ConcreteClassA();
// some assignements
return $object;
}
}
And how this code is used:
class SomeClass
{
/** #var ConcreteClassA $propertyA */
public $propertyA;
/** #var ConcreteClassB $propertyB */
public $propertyB;
public function someMethod()
{
$this->propertyA = $this->propertyB->someMethodA($params);
$this->someProperty->someOtherMethod($this->propertyA);
// again, someOtherMethod expects ConcreteClassA but AbstractClassA given...
}
I tried to "play" with #template without success...
Please also note that I have limited control over abstract classes.
Thanks,
I'm trying to write a unit test for the startedAt() method using mocks however the problem I'm facing is that I don't think I can access the builder instance from inside that startedAt() method.
To test the startedAt() method I created a fixture class called ExampleFilters and had it extend the parent class of Filters. Inside of the ExampleFilters class I import the FiltersByStartDate trait.
Does anyone have any suggestions on how I can access the builder property from the FiltersByStartDate trait?
Any ideas on this?
<?php
namespace App\Filters\Concerns;
trait FiltersByStartDate
{
/**
* Filter a query to include models of a specific date started.
*
* #param array $startedAt
* #return \Illuminate\Database\Eloquent\Builder
*/
public function startedAt($startedAt)
{
if (isset($startedAt[1])) {
$this->builder->whereHas('currentEmployment', function ($query) use ($startedAt) {
$query->whereBetween('started_at', [
$startedAt[0],
$startedAt[1]
]);
});
} else {
$this->builder->whereHas('currentEmployment', function ($query) use ($startedAt) {
$query->whereDate('started_at', $startedAt[0]);
});
}
return $this->builder;
}
}
<?php
namespace Tests\Fixtures;
use App\Filters\Concerns\FiltersByStartDate;
use App\Filters\Filters;
class ExampleFilters extends Filters
{
use FiltersByStartDate;
}
<?php
namespace App\Filters;
use Illuminate\Http\Request;
abstract class Filters
{
/**
* #var \Illuminate\Http\Request
*/
protected $request;
/**
* The Eloquent builder.
*
* #var \Illuminate\Database\Eloquent\Builder
*/
protected $builder;
/**
* Registered filters to operate upon
*
* #var array
*/
protected $filters = [];
/**
* Create a new class instance.
*
* #param \Illuminate\Http\Request $request
*/
public function __construct(Request $request)
{
$this->request = $request;
}
/**
* Apply the filters.
*
* #param \Illuminate\Database\Eloquent\Builder $builder
* #return \Illuminate\Database\Eloquent\Builder
*/
public function apply($builder)
{
$this->builder = $builder;
foreach ($this->getFilters() as $filter => $value) {
if (method_exists($this, $filter)) {
$this->$filter($value);
}
}
return $this->builder;
}
/**
* Fetch all relevant filters from the request.
*
* #return array
*/
public function getFilters()
{
return array_filter($this->request->only($this->filters));
}
}
<?php
namespace Tests\Unit\Filters\Concerns;
use Illuminate\Database\Query\Builder;
use Tests\Fixtures\ExampleFilters;
use Tests\TestCase;
/*
* #group filters
*/
class FiltersByStartDateTest extends TestCase
{
/* #var Tests\Fixtures\ExampleFilters */
protected $subject;
public function setUp(): void
{
$this->subject = app(ExampleFilters::class);
}
/** #test */
public function models_can_be_filtered_by_their_start_date()
{
// $this->markTestIncomplete();
$dateSet = ['2020-01-01 00:00:00'];
$mock = \Mockery::mock(Builder::class)
->shouldReceive('whereHas', \Mockery::any())
->shouldReceive('whereDate')
->withArgs(['started_at', $dateSet])
->once()
->andReturn(true)
->getMock();
dd($this->subject->startedAt($dateSet));
$builderMockFromDate = $this->subject->startedAt($dateSet);
$this->assertSame($builderMockFromDate, $mock);
}
}
I have the following phpunit test for testing the controllers:
The DefaultControllerTest:
namespace Tests\AppBundle\Controller;
use Tests\AppBundle\Controller\BasicHttpController;
use AppBundle\DataFixtures\Test\DummyUserFixtures;
/**
* #testtype Functional
*/
class DefaultControllerTest extends BasicHttpController
{
/**
* {#inheritdoc}
*/
public function setUp()
{
$fixture = new DummyUserFixtures();
$fixture->load($this->entityManager);
}
/**
* Testing the Behavior when visiting the index page
*/
public function testIndex()
{
$client = $this->client;
$router=$client->getContainer()->get('router');
$crawler = $client->request('GET', '/');
$response=$client->getResponse();
$this->assertTrue($client->getResponse()->isRedirect());
$this->assertEquals($router->getRouteCollection()->get('fos_user_security_login')->getPath(),$response->headers->get('Location'));
//#todo Create Dummy Users
// $this->checkPanelAfterSucessfullLogin($crawler);
}
}
That extends the following test BasicHttpController (try to apply the DRY principle):
namespace Tests\AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Doctrine\Common\DataFixtures\Purger\ORMPurger;
class BasicHttpController extends WebTestCase
{
protected $entityManager=null;
protected $client=null;
/**
* {#inheritdoc}
*/
public function __construct()
{
parent::__construct();
$this->client = static::createClient();
$container = $this->client->getContainer();
$doctrine = $container->get('doctrine');
$this->entityManager=$doctrine->getManager();
}
/**
* Remove all entities from the database
*/
protected function truncateEntities()
{
$purger = new ORMPurger($this->entityManager());
$purger->purge();
}
/**
* {#inheritdoc}
*/
public function tearDown()
{
$this->truncateEntities();
}
/**
* #param username String the user's username
* #param passwoρd String the user's password
*/
protected function checkPanelAfterSucessfullLogin($crawler,string $username,string $password)
{
//Submitting the form
$form=$crawler->selectButton('_submit')->form();
$form['_username']=$username;
$form['_password']=$password;
$crawler=$crawler->submit($form);
$response=$client->getResponse();
$this->assertTrue($client->getResponse()->isRedirect());
$client->followRedirect();
//Checking header
$headerDom=$crawler->filter('header')->childen()->filter('nav.navbar')->children();
$this->assertCount(1,$headerDom->find('a.navbar-brand')); //homepage link
$this->assertCount(1,$headerDom->find('a.btn-danger')); //Logout button
}
}
As you can see I try to load the following fixture:
namespace AppBundle\DataFixtures\Test;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\Common\Persistence\ObjectManager;
class DummyUserFixtures extends AbstractFixture implements OrderedFixtureInterface,ContainerAwareInterface
{
/**
* #var ContainerInterface
*/
private $container=null;
/**
* {#inheritDoc}
*/
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
/**
* Generic function that creates a user with provided information.
* #param $name {String} The user's name
* #param $surname {String} The user's surname
* #param $username {String} The user's username
* #param $password {String} The user's password
* #param $email {String} The user's recovery email
* #param $role {String} The user's system role
* #param $phone {String | null} The user's phone number
* #param $organization {String|null} The user's organization
* #param $occupation {String|null} The user's occupation
*
* #return AppBundle\Entity\User
*/
private function createUser($name,$surname,$username,$password,$email,$role,$phone=null,$organization=null,$occupation=null)
{
$fosUserManager=$this->container->get('fos_user.user_manager');
/**
* #var AppBundle\Entity\User
*/
$user=$fosUserManager->createUser();
$user->setUsername($username);
$user->setEmail($email);
$user->setPlainPassword($password);
$user->setEnabled(true);
$user->setRoles(array($role));
$user->setName($name);
$user->setSurname($surname);
if($phone){
$user->setPhone($phone);
}
if($organization){
$user->setOrganization($organization);
}
if($occupation){
$user->setOccupation($occupation);
}
$fosUserManager->updateUser($user, true);
return $user;
}
/**
* {#inheritDoc}
*/
public function load(ObjectManager $manager)
{
$this->createUser('John','Doe','jdoe','simplepasswd','jdoe#example.com','ROLE_USER','+3021456742324','Acme Products','Soft Engineer');
$this->createUser('Jackie','Chan','jchan','thesimplepasswd','jackiechan#example.com','ROLE_ADMIN','+302141232324','Holywood','Actor');
$this->createUser('Chuck','Norris','chuck_norris','unhackablepasswd','chucknorris#example.com','ROLE_SUPERADMIN',null,'Universe','Master');
}
public function getOrder()
{
return 1;
}
}
But for some reason I get the following error:
There was 1 error:
1) Tests\AppBundle\Controller\DefaultControllerTest::testIndex
Error: Call to a member function get() on null
/home/vagrant/code/src/AppBundle/DataFixtures/Test/DummyUserFixtures.php:50
/home/vagrant/code/src/AppBundle/DataFixtures/Test/DummyUserFixtures.php:87
/home/vagrant/code/tests/AppBundle/Controller/DefaultControllerTest.php:19
Further debugging has proved that the error is triggered by the following line in DummyUserFixtures:
$fosUserManager=$this->container->get('fos_user.user_manager');
So do you know how to load the data via fixtures?
In order to get it working you should set the service container you generate from the static::createClient() method and pass it via the $fixture->setContainer($container)
So a good approach is to define the container as protected instance variable to the BasicHttpController so any Test class (eg. the DefaultControllerTest in your case) is able to load the fixtures accordingly.
So using the setUp method and instance variables of BasicHttpController should be the following:
//Namespace declaration goes there
class BasicHttpController extends WebTestCase
{
protected $entityManager=null;
protected $client=null;
protected $container=null;
/**
* {#inheritdoc}
*/
public function setUp()
{
$this->client = static::createClient();
$this->container = $this->client->getContainer();
$doctrine = $this->container->get('doctrine');
$this->entityManager=$doctrine->getManager();
}
// Rest methods here
}
Note: on classes that are getting inherited from BasicHttpController you can define the setUp like that:
public function setUp()
{
parent::setUp();
// Add extra stuff here
}
So you can do more setUp bootstrapping before tests.
This function is in helper I am using zf2 version 2.4 I am beginner in zend please help me.
I tried this:
function getUrlArray(){
$helperUrl = new Url(); // use Zend\View\Helper\Url;
$op = $helperUrl->url();
print_r($op);
}
I am getting this error:
Fatal error: Call to undefined method Zend\View\Helper\Url::url()
Try this ViewHelper :
<?php
namespace YourNamespace\View\Helper\Service;
use YourNamespace\View\Helper\CurrentUri;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class CurrentUriFactory implements FactoryInterface
{
/**
* #param ServiceLocatorInterface $serviceLocator
* #return CurrentUri
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$helper = new CurrentUri();
$helper->setRequest($serviceLocator->getServiceLocator()->get('Request'));
return $helper;
}
}
<?php
namespace YourNamespace\View\Helper;
use Zend\Stdlib\RequestInterface;
use Zend\View\Helper\AbstractHelper;
/**
* Helper: $this->currentUri();
*/
class CurrentUri extends AbstractHelper
{
/**
* #var \Zend\Http\PhpEnvironment\Request
*/
protected $request;
/**
* #return string
* #see \Zend\Http\PhpEnvironment\Request
* #see \Zend\Uri\Uri
*/
public function __invoke()
{
return $this->getRequest()->getUri()->toString();
}
/**
* #return \Zend\Http\PhpEnvironment\Request
*/
public function getRequest()
{
return $this->request;
}
/**
* #param RequestInterface $request
* #return CurrentUri
*/
public function setRequest(RequestInterface $request)
{
$this->request = $request;
return $this;
}
}