How to define an accessor in Laravel 9? - laravel-9

I noticed there are two ways to define an accessor in Laravel 9:
protected function title(): Attribute
{
return Attribute::make(
get: function () {
return $this->Library->Book->name . ' at ' . $this->Library->name;
}
);
}
But also:
public function getTitleAttribute()
{
return $this->Library->Book->name . ' at ' . $this->Library->name;
}
Which method is preferred and why?

Related

Yielding from a PHP method

I am trying to use yield in PHP 7.3, from a class method:
<?php
class X {
public $x;
public function __construct($x) {
$this->x = $x;
}
public function call_direct() {
return $this->x;
}
public function call_yield() {
return function() {
yield $this->x;
};
}
}
$a = new X(42);
echo "direct: " . $a->call_direct(), "\n";
$iter = $a->call_yield();
foreach ($iter as $n) {
echo "yielded: $n\n";
}
Naturally, this outputs direct: 42... but not the second line. What am I missing to get it to output yielded: 42 as well? Is this actually possible in PHP these days?
(Obviously my actual example iterates over a list, but I have trimmed it down to the essential).

Doctrine ORM create method phpspec test failure

I try to write, at first glance, it would seem a trivial test for my repository's "update" method:
<?php
declare(strict_types=1);
namespace Paneric\Authorization\ORM\Repository;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\ORMException;
use Paneric\Authorization\DTO\FieldDTO;
use Paneric\Authorization\ORM\Entity\Field;
use Doctrine\ORM\EntityRepository;
use Paneric\Authorization\Interfaces\FieldRepositoryInterface;
class FieldRepository extends EntityRepository implements FieldRepositoryInterface
{
const ENTITY_CLASS = Field::class;
public function __construct(EntityManagerInterface $_em)
{
parent::__construct($_em, $_em->getClassMetadata(self::ENTITY_CLASS));
}
...
public function update(int $fieldId, FieldDTO $fieldDTO): void
{
try {
$field = $this->find($fieldId);
$field->transfer($fieldDTO);
$this->_em->flush();
} catch (ORMException $e) {
echo $e->getMessage();
}
}
...
}
with a spec method:
<?php
namespace spec\Paneric\Authorization\ORM\Repository;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\QueryBuilder;
use Paneric\Authorization\DTO\FieldDTO;
use Paneric\Authorization\ORM\Entity\Field;
use Paneric\Authorization\ORM\Repository\FieldRepository;
use Doctrine\ORM\AbstractQuery;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class FieldRepositorySpec extends ObjectBehavior
{
public function let(EntityManagerInterface $_em, ClassMetadata $classMetadata)
{
$_em->getClassMetadata(Field::class)->willReturn($classMetadata);
$this->beConstructedWith($_em);
}
...
public function it_updates(Field $field, FieldDTO $fieldDTO, EntityManagerInterface $_em)
{
$fieldId = 1;
$field = $this->find($fieldId);
$field->transfer($fieldDTO)->shouldBeCalled();
$_em->flush()->shouldBeCalled();
$this->update($fieldId, $fieldDTO);
}
...
}
and receive the following error:
Unexpected method call on Double\EntityManagerInterface\EntityManagerInterface\P1:
- find(
null,
1,
null,
null
)
expected calls were:
- getClassMetadata(
exact("Paneric\Authorization\ORM\Entity\Field")
)
- find(
exact("Paneric\Authorization\ORM\Entity\Field"),
exact(1)
)
- flush(
)
Apparently issue is related to the call:
...
$field = $this->find($fieldId);
...
Although the second remark related to getClassMetadata, looks strange, considering the fact that my spec let method:
public function let(EntityManagerInterface $_em, ClassMetadata $classMetadata)
{
$_em->getClassMetadata(Field::class)->willReturn($classMetadata);
$this->beConstructedWith($_em);
}
does its job in case of other spec tests.
Can anyone help me to solve this issue ? Thx in advance.
In my repository's "update" metod, line:
$field = $this->find($fieldId);
has to be replaced by:
$field = $this->_em->find(Field::class, $fieldId);
so the complete spec test looks like:
public function it_updates(Field $field, FieldDTO $fieldDTO, EntityManagerInterface $_em)
{
$fieldId = 1;
$_em->find(Field::class, $fieldId)->willReturn($field);
$field->transfer($fieldDTO)->shouldBeCalled();
$_em->flush()->shouldBeCalled();
$this->update($fieldId, $fieldDTO);
}

How to fix this DEPRECATION error in codeception?

I am using codeception,when I try to check dbconnection it shows the error:
> DEPRECATION: Calling the
> "Symfony\Component\EventDispatcher\EventDispatcherInterface::dispatch()"
> method with the event name as first argument is deprecated since
> Symfony 4.3, pass it second and provide the event object first
> instead.
> C:\xampp\htdocs\affiliate_codeception\codeception\vendor\symfony\event-dispatcher\EventDispatcher.php:58"
How do I fix this?
<?php
class adminTest extends \Codeception\Test\Unit
{
/**
* #var \UnitTester
*/
protected $tester;
protected function _before()
{
}
protected function _after()
{
}
// tests
public function testSomeFeature()
{
}
public function tryToTest(UnitTester $I)
{
$I->amConnectedToDatabase('testdb');
//$I->seeInDatabase('users', ['name' => 'Davert', 'email' => 'davert#mail.com']);
}
}
Change the code in vendor/codeception/phpunit-wrapper/src/Listener.php:
Search for
dispatcher->dispatch(
For each of them, swap the first and second arguments.
For example, the first occurrence is:
public function startTestSuite(\PHPUnit\Framework\TestSuite $suite)
{
$this->dispatcher->dispatch('suite.start', new SuiteEvent($suite));
}
Change it to:
public function startTestSuite(\PHPUnit\Framework\TestSuite $suite)
{
$this->dispatcher->dispatch(new SuiteEvent($suite), 'suite.start');
}

PHP Youshido GraphQL issue with nested fields

I am using version v1.4.2.18. The library can be found here: https://github.com/Youshido/GraphQL
I am trying to accomplish the following:
query {
articleSummary(id:1) {
title,
body,
article {
id
}
}
}
I have an ArticleSummaryField.php:
class ArticleSummaryField extends AbstractField
{
public function build(FieldConfig $config)
{
$config->addArgument('id', new NonNullType(new StringType()));
}
public function getType()
{
return new ArticleSummaryType();
}
public function resolve($value, array $args, ResolveInfo $info)
{
return [
'title' => 'test title',
'body' => 'test body',
'article' => $args['id']
];
}
}
Then the ArticleSummaryType.php:
class ArticleSummaryType extends AbstractObjectType
{
public function build($config)
{
$config
->addField('title', new StringType());
->addField('body', new StringType());
->addField('article', new ArticleField());
}
}
Then the ArticleField.php has the getType method return the ArticleType which has the id field.
However what i am getting is an error:
Fatal error: Uncaught Error: Call to undefined method ArticleField::getNullableType() in .../vendor/youshido/graphql/src/Execution/Processor.php on line 135
What seems to be happening is that when $targetField->getType() on line 135 in src/Execution/Processor.php is called its returning the ArticleField class, not the ArticleType class.
I would expect that to return the class as declared in the 'getType' method on the ArticleField class.
Am i going about this wrong for nesting fields? Or is there a bug in the library?
To accomplish this you only pass the Field class as the first argument.
class ArticleSummaryType extends AbstractObjectType
{
public function build($config)
{
$config
->addField('title', new StringType());
->addField('body', new StringType());
->addField(new ArticleField());
}
}
Then in the field class you can override getName to set the name for the field as needed or it will use the class name as the field name.

How to load a template file from my admin controller in custom module in prestashop

How to load a template file from my admin controller in custom module in prestashop 1.6
if (!defined('_PS_VERSION_')) exit;
class QueryAllTrxController extends ModuleAdminController
{
public $module;
public function __construct()
{
parent::__construct();
}
public function initContent()
{
parent::initContent();
$this->setTemplate('display.tpl');
//$this->setTemplate(_PS_THEME_DIR_.'mypage.tpl');
}
}
I had the same problem and it took forever to figure out.
I ended up spotting the solution in this video : https://www.youtube.com/watch?v=CdnJpLqqvcM
Any this is how I got it to work :
1 - Create the controller in ModuleName/controllers/AdminMyControllerNameController.php
class AdminMyControllerNameController extends ModuleAdminController
{
public function __construct()
{
$this->display = 'view';
$this->meta_title = $this->l('metatitle');
$this->toolbar_title = $this->l('tollbartitle');
parent::__construct();
}
public function initContent()
{
$this->show_toolbar = true;
$this->display = 'view';
$this->meta_title = $this->l('META TITLE');
parent::initContent();
$this->setTemplate('templatename.tpl');
}
public function initToolBarTitle()
{
$this->toolbar_title = $this->l('TOOLBAR TITLE??');
}
public function initToolBar()
{
return true;
}
}
2 - Create the template file in ModuleName/views/admin/my_controller_name/template.tpl
You have to create a directory in the views/admin folder using the name of your controller written in snake case.
Anyway I hope this will help.
WORKING CODE HERE
Background:
You want to add a custom admin page with a custom module controller. But you cannot customize template because you're stuck with this error message:
Fatal error: Uncaught --> Smarty: Unable to load template file '/var/www/html/admin-dev/themes/default/template/catalog/index.tpl' <-- thrown in /var/www/html/tools/smarty/sysplugins/smarty_internal_templatebase.php on line 129
Your current source code is:
class AdminYourModuleNameProductsController extends ModuleAdminController {
public function initContent() {
parent::initContent();
// enable these lines if you're stuck with damn stupid blank page with just 500 error
// ini_set('display_errors', '1');
// ini_set('display_startup_errors', '1');
// error_reporting(E_ALL);
$this->setTemplate('products/index.tpl');
}
}
And you don't know what to do because PrestaShop dev doc is the worst document in the history of ecommerce platform developer document and moreover its forum is full of chitchats and junks.
Solution
Place index.tpl at
{%PRESTA_ROOT%}/modules/{%YOUR MODULE DIR%}/views/templates/admin/{% snake case version of controller %}/products/index.tpl
For example, if your module name is yourmodulename and the controller name is AdminYourModuleNameProductsController (as in the example), the correct path is:
{%PRESTA_ROOT%}/modules/yourmodulename/views/templates/admin/your_module_name_products/products/index.tpl
If the error still persists:
Check this line:
{%PRESTA_ROOT%}/classes/controller/ModuleAdminController.php
public function createTemplate($tpl_name)
{
if (file_exists(_PS_THEME_DIR_.'modules/'.$this->module->name.'/views/templates/admin/'.$tpl_name) && $this->viewAccess()) {
// echo the following line and exit
return $this->context->smarty->createTemplate(_PS_THEME_DIR_.'modules/'.$this->module->name.'/views/templates/admin/'.$tpl_name, $this->context->smarty);
} elseif (file_exists($this->getTemplatePath().$this->override_folder.$tpl_name) && $this->viewAccess()) {
// echo the following line and exit
return $this->context->smarty->createTemplate($this->getTemplatePath().$this->override_folder.$tpl_name, $this->context->smarty);
}
// the error occurs because php get reach to the following line:
return parent::createTemplate($tpl_name);
}
Do as I commented and you can get the correct file path. Make sure the file exists in the path.
My PrestaShop version is 1.6.1.24
The code $this->setTemplate('display.tpl'); is loading a template file modules/your-custom-module/views/templates/admin/display.tpl or modules/your-custom-module/display.tpl.
The classname must be named that way: AdminQueryAllTrxController
you can put display.tpl in :
modules\module_name\views\templates\admin\classe_name(QueryAllTrx)
and use :$this->setTemplate('display.tpl'); in your AdminQueryAllTrxController
First of all add controller to your module:
modules\module_name\controllers\admin\SomeNameController.php
and extend it by ModuleAdminController, you need at least two methods for it to work properly __construct and initContent
put the following code to the later method:
$this->content .= $this->context->smarty->fetch($this->pathToTpl);
$this->context->smarty->assign(array(
'content' => $this->content,
));
You could replace $this->pathToTpl with any path which is pointed to your tpl file, I'm prefer to create the path dynamically. You can see a simple example here:
class SomeNameController extends ModuleAdminController{
var $pathToTpl;
public function __construct()
{
$this->bootstrap = true;
$this->context = Context::getContext();
$this->pathToTpl = _PS_MODULE_DIR_ .
$this->module->name . // put the name of module
'/views/templates/admin' .
'/' .
'templateName.tpl';
parent::__construct();
}
public function initContent()
{
parent::initContent();
$this->content .= $this->context->smarty->fetch($this->pathToTpl);
$this->context->smarty->assign(array(
'content' => $this->content,
));
}
}
finally you need to place templateName.tpl in the path you wanted to be:
modules\module_name\views\templates\admin\templateName.tpl