spryker extend DummyPaymentHandlerPlugin class - spryker

I am new to spryker and I want to extend this class DummyPaymentHandlerPlugin. I tried by adding the class to the factory but is not working. Can anyone help me to do this

Extending plugins in Spryker is possible. But instead of changing the factory method, you just have to change the use statement in the appropriate dependency provider.
In your case, it's \Pyz\Yves\CheckoutPage\CheckoutPageDependencyProvider::extendPaymentMethodHandler:
protected function extendPaymentMethodHandler(Container $container): Container
{
$container->extend(static::PAYMENT_METHOD_HANDLER, function (StepHandlerPluginCollection $paymentMethodHandler) {
$paymentMethodHandler->add(new DummyPaymentHandlerPlugin(), DummyPagmentConfig::PAYMENT_PROVIDER_NAME);
return $paymentMethodHandler;
});
return $container;
}

Related

how to use Symfony methods Action excluding the "Action" word

I am currently migrating an existent application to Symfony2 that has about 100 controllers with approximately 8 actions in each controller. All the current Actions are named as follow:
public function index(){}
However the default naming convention for Symfony is indexAction().
Is it possible to keep all my current actions and tell Symfony to use as it is without the "Action" word after the method name?
thank you.
Yes, this is possible. You should be able to define routes as normal, but you need to change the way the kernel finds the controller. The best way to do this is to replace/decorate/extends the service 'controller_name_converter'. This is a private service and is injected into the 'controller_resolver' service.
The source code of the class you want to replace is at 'Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser'.
Basically, the code runs like this. The 'bundle:controller:action' you specified when creating the route is saved in the cache. When a route is matched, that string is given back to the kernel, which in turn calls 'controller_resolver' which calls 'controller_name_resolver'. This class convert the string into a "namespace::method" notation.
Take a look at decorating services to get an idea of how to do it.
Here is an untested class you can work with
class ActionlessNameParser
{
protected $parser;
public function __construct(ControllerNameParser $parser)
{
$this->parser = $parser;
}
public function parse($controller)
{
if (3 === count($parts = explode(':', $controller))) {
list($bundle, $controller, $action) = $parts;
$controller = str_replace('/', '\\', $controller);
try {
// this throws an exception if there is no such bundle
$allBundles = $this->kernel->getBundle($bundle, false);
} catch (\InvalidArgumentException $e) {
return $this->parser->parse($controller);
}
foreach ($allBundles as $b) {
$try = $b->getNamespace().'\\Controller\\'.$controller.'Controller';
if (class_exists($try)) {
// You can also try testing if the action method exists.
return $try.'::'.$action;
}
}
}
return $this->parser->parse($controller);
}
public function build($controller)
{
return $this->parser->build($controller);
}
}
And replace the original service like:
actionless_name_parser:
public: false
class: My\Namespace\ActionlessNameParser
decorates: controller_name_converter
arguments: ["#actionless_name_parser.inner"]
Apparently the Action suffix is here to distinguish between internal methods and methods that are mapped to routes. (According to this question).
The best way to know for sure is to try.
// src/AppBundle/Controller/HelloController.php
namespace AppBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class HelloController
{
/**
* #Route("/hello/{name}", name="hello")
*/
public function indexAction($name)
{
return new Response('<html><body>Hello '.$name.'!</body></html>');
}
}
Try to remove the Action from the method name and see what happens.

PHPUnit test if class methods were called

I have model class that calls mailer class inside one of its methods:
class someModel{
public function sendEmail($data){
$mailer = new Mailer();
$mailer->setFrom($data['from']);
$mailer->setTo($data['to']);
$mailer->setSubject($data['subject']);
return $mailer->send();
}
}
How can I test sendEmail method? Maybe I should mock mailer class and check if all these mailer methods were called in sendMail method?
Your help would be appreciated.
IMO wrapping the Mailer class does not solve the problem you're facing, which is you don't have control over the Mail instance being used.
The problem comes from creating the dependencies inside the object that needs them instead of injecting them externally like this:
class someModel{
private $mailer;
public function __construct(Mailer $mailer) {
$this->mailer = $mailer;
}
public function sendEmail($data){
$this->mailer->setFrom($data['from']);
$this->mailer->setTo($data['to']);
$this->mailer->setSubject($data['subject']);
return $this->mailer->send();
}
}
When creating the someModel instance, you must pass a Mail instance (which is an external dependency). And in the test you can pass a Mail mock that will check that the correct calls are being made.
Alternative:
If you feel that injecting a Mail instance is bad (maybe because there are lots of someModel instances), or you just can't change your code this way, then you could use a Services repository, that will keep a single Mail instance and that allows you to set it externally (again, in the test you would set a mock).
Try a simple one like Pimple.
I would (and have in my own code with Mailer!) wrap your instance of Mailer inside a class that you write. In other words, make your own Email class that uses Mailer under the hood. That allows you to simplify the interface of Mailer down to just what you need and more easily mock it. It also gives you the ability to replace Mailer seamlessly at a later date.
The most important thing to keep in mind when you wrap classes to hide external dependencies is keep the wrapper class simple. It's only purpose is to let you swap out the Email libraries class, not provide any complicated logic.
Example:
class Emailer {
private $mailer = new Mailer();
public function send($to, $from, $subject, $data) {
$this->mailer->setFrom($from);
$this->mailer->setTo($to);
...
return $mailer->send();
}
}
class EmailerMock extends Emailer {
public function send($to, $from, $subject, $data) {
... Store whatever test data you want to verify ...
}
//Accessors for testing the right data was sent in your unit test
public function getTo() { ... }
...
}
I follow the same pattern for all classes/libraries that want to touch things external to my software. Other good candidates are database connections, web services connections, cache connections, etc.
EDIT:
gontrollez raised a good point in his answer about dependency injection. I failed to explicitly mention it, but after creating the wrapper the way you would want to use some form of dependency injection to get it into the code where you want to use it. Passing in the instance makes it possible to setup the test case with a Mocked instance.
One method of doing this is passing in the instance to the constructor as gontrollez recommends. There are a lot of cases where that is the best way to do it. However, for "external services" that I am mocking I found that method became tedious because so many classes ended up needing the instance passed in. Consider for example a database driver that you want to Mock for your tests, but you use in many many different classes. So instead what I do is create a singleton class with a method that lets me mock the whole thing at once. Any client code can then just use the singleton to get access to a service without knowing that it was mocked. It looked something like this:
class Externals {
static private $instance = null;
private $db = null;
private $email = null;
...
private function __construct() {
$this->db = new RealDB();
$this->mail = new RealMail();
}
static function initTest() {
self::get(); //Ensure instance created
$db = new MockDB();
$email = new MockEmail();
}
static function get() {
if(!self::$instance)
self::$instance = new Externals();
return self::$instance;
}
function getDB() { return $this->db; }
function getMail() { return $this->mail; }
....
}
Then you can use phpunit's bootstrap file feature to call Externals::initTest() and all your tests will be setup with the mocked externals!
First, as RyanW says, you should write your own wrapper for Mailer.
Second, to test it, use a mock:
<?php
class someModelTest extends \PHPUnit_Framework_TestCase
{
public function testSendEmail()
{
// Mock the class so we can verify that the methods are called
$model = $this->getMock('someModel', array('setFrom', 'setTo', 'setSubject', 'send'));
$controller->expects($this->once())
->method('setFrom');
$controller->expects($this->once())
->method('setTo');
$controller->expects($this->once())
->method('setSubject');
$controller->expects($this->once())
->method('send');
$model->sendEmail();
}
}
The above code is untested, but it basically mocks the someModel class, creating dummy functions for each each function called within sendEmail. It then tests to make sure each of the functions called by sendEmail is called exactly once when sendEmail is called.
See the PHPUnit docs for more info on mocking.

How to include Facebook-SDK

I'm using an example of FOSUserBundle with FOSFacebookBundle. Hereon i have build my application.
The relevant Project Structure is like following:
src\ABC\MainBundle\
src\ABC\UserBundle\
src\ABC\MainBundle\Controller\DefaultController.php
src\ABC\UserBundle\Security\User\Provider\FacebookProvider.php
vendor\facebook\php-sdk\src\base_facebook.php
Part of the FacebookProvider:
use \BaseFacebook;
use \FacebookApiException;
class FacebookProvider implements UserProviderInterface
{
protected $facebook;
public function __construct(BaseFacebook $facebook, $userManager, $validator)
{
$this->facebook = $facebook;
}
public function loadUserByUsername($username)
{
try {
$fbdata = $this->facebook->api('/me');
...
As you can see there is the Facebook-Object already available.
What i want to do now is nearly the same, but in my DefaultController:
use \BaseFacebook;
use \FacebookApiException;
class DefaultController extends BaseController
{
public function indexAction(){
$facebook = new Facebook('key', 'secret');
$fbfriends_obj = $facebook->api('/'.$fbid.'/friends');
...
But there i get the message
Fatal error: Class 'ABC\MainBundle\Controller\Facebook' not found in C:\xampp\htdocs\...\src\ABC\MainBundle\Controller\DefaultController.php on line x
Why is that? How can i access the facebook-class from inside my defaultcontroller? If its already possible for the facebookprovider, why it aint possible for my controller?
any hints will be really appreciated!
The solution to that problem is, that the facebook-class has no namespace and you have to do something like
$facebook = new \Facebook(...)
Problem is here:
use \BaseFacebook;
use \FacebookApiException;
You are importing BaseFacebook class from namespace you should use \Facebook (in Controller and FacebookProvider classes)

PHPUnit::How can be __construct with protected variables tested?

PhpUnit::How can be __construct with protected variables tested?
(not always we should add public method getVal()- soo without add method that return protected variable value)
Example:
class Example{
protected $_val=null;
function __construct($val){
$this->_val=md5 ($val);
}
}
Edit:
also exist problem to test in function that return void
Edit2:
Example why we need test __construct:
class Example{
protected $_val=null;
//user write _constract instead __construct
function _constract($val){
$this->_val=md5 ($val);
}
function getLen($value){
return strlen($value);
}
}
class ExampleTest extends PHPUnit_Framework_TestCase{
test_getLen(){
$ob=new Example();//call to __construct and not to _constract
$this->assertEquals( $ob->getLen('1234'), 4);
}
}
test run ok, but Example class "constructor" wasn't created!
Thanks
The main goal of unit testing is to test interface By default, you should test only public methods and their behaviour. If it's ok, then your class is OK for external using. But sometimes you need to test protected/private members - then you can use Reflection and setAccessible() method
Create a derived class that exposes the value that you want to test.

How to draw to a sprite outside of a class

I'm wondering (based on scoping rules) how I might do the following:
I want to draw to a sprite that exists on the main stage in which I have a class instantiated.
So something like
public function MyClass(reference:String){
this.reference = reference;
}
public function drawToOutsideSprite(){
this.parent.getChildByName(this.reference).addChild(someLoaderName);
}
Would I use super() in this case, or what's the usual methodology?
Thanks,
jml
There are a few ways to do this. I'm assuming your MyClass extends Sprite.
package
{
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Sprite;
/**
* MyClass
*/
public class MyClass extends Sprite
{
public var referenceA:String;
public var referenceB:Sprite;
public function get referenceA_way2():Sprite
{
return this.parent.getChildByName(referenceA);
}
/**
* MyClass Constructor
*/
public function MyClass(referenceA:String = null, referenceB:Sprite = null)
{
super();
this.referenceA = referenceA;
this.referenceB = referenceB;
}
public function drawToOutsideSpriteA(child:DisplayObject):void
{
// referenceA
this.parent.getChildByName(this.referenceA).addChild(child);
// or
referenceA_way2.addChild(child);
}
public function drawToOutsideSpriteB(child:DisplayObject):void
{
// referenceB
referenceB.addChild(child);
}
public function drawToOutsideSpriteC(referenceC:String, child:DisplayObject):void
{
this.parent.getChildByName(referenceC).addChild(child);
}
// Do this:
// it allows you to abstract out the logic of getting the main sprite
// into some util class, so you could reuse that functionality elsewhere,
// and so your code is cleaner.
public function drawToOutsideSpriteD(child:DisplayObject):void
{
StageUtil.getMainSprite().addChild(child);
}
}
}
package
{
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Sprite;
/**
* MyClass
*/
public class StageUtil
{
private static var root:Stage;
/**
* Called when app first starts
*/
public static function initialize(stage:Stage):void
{
root = stage;
}
public static function getMainSprite():DisplayObjectContainer
{
return root; // or something more complex,
// like a recursive function to getSpriteByName
}
public static function addToStage(child:DisplayObject):DisplayObject
{
return getMainSprite().addChild(child);
}
}
}
In general I would abstract out the logic for getting the "main" sprite into some util/manager class, because you don't want to hardcode that into your MyClass, as you might need it in other places, and you might want to customize it later on. It sounds like your just asking what's the best way to reference sprites outside of the scope of the MyClass, so I say just put it into the Util, assuming it has good reason for being their (like FlexGlobals.topLevelApplication in Flex, so you can easily access the application).
I don't recommend passing in id's or name's into the constructor and doing it that way, I don't really recommend constructor arguments at all. I would just pass those into a method if you needed to, or have it built into the class itself, or the Util.
To clear up the scoping question a little... You normally don't want to draw to sprites outside the scope of the class you are in, unless they have some special functionality that will be referenced by multiple classes with totally different scopes. This is because things would start not making sense, who's being added to who. But some good examples on when to do thatinclude:
Buttons with ToolTips: Tooltips are added to the root because they appear on top of everything, but a Button could be 20 children deep, so you'd have in the Button subclass, perhaps, addToolTip(child).
PopUps: You might want to add a popup from within MyClass, but it's really being added to the stage. In flex this is like PopUpManager.addPopUp(child), just like the sample StageUtil.getMainSprite().addChild(child). You could even wrap that method so it's like the one in the class above, addToStage.
Transform/Drawing Stage: If you have some global painting stage, or place where you scale/resize things, you might want to be able to add/remove graphics from that from any class.
The super() method isn't useful in this scenario. The only time you really use super() is if you have overridden a method, and want to access the super-classes implementation. Something like this (assuming you're extending Sprite):
override public function addChild(child:DisplayObject):DisplayObject
{
if (child is MyDrawingSprite)
return StageUtil.addToStage(child); // add to main stage
else
return super.addChild(child); // add directly to this class
}
Otherwise, try to stick to just adding children directly to the "MyClass".
Hope that helps.

Resources