Oct 9, 2017

Magento2 - Unittest with Object manager

As much as possible avoid using object manager to create object on magento if your going to create unittest on it. Use the Factory instead but in some case some plugins(Unirgy) love the object manager. Then when you override there class you will getting headache on creating unittest.

One of the error you will encounter was
"Expectation failed for method name is equal to <string:create> when invoked zero or more times" this  happen  you call create method  multiple times.
Sample:

 /** @var \Winz\Sales\Api\Data\OrderInvoiceResultInterface */
$orderInvoiceResultInterface = $this->getMockBuilder('Winz\Sales\Api\Data\OrderInvoiceResultInterface')
    ->disableOriginalConstructor()              
    ->setMethods(['setOrder', 'setInvoice', 'getOrder', 'getInvoice', ])
    ->getMock();      
$orderInvoiceResult = $objectManagerInterface
    ->expects($this->any())
    ->method('create')
    ->with('Storm\Sales\Api\Data\OrderInvoiceResultInterface')
    ->willReturn($orderInvoiceResultInterface);
/** @var \Winz\Sales\Api\Data\OrderResultInterface */
$orderResultInterface = $this->getMockBuilder('Winz\Sales\Api\Data\OrderResultInterface')
    ->disableOriginalConstructor()
    ->setMethods(['setId', 'setNo', 'getId', 'getNo'])
    ->getMock();      
$orderResult = $objectManagerInterface
    ->expects($this->once())
    ->method('create') 
  ->with('Winz\Sales\Api\Data\OrderResultInterface')
    ->willReturn($orderResultInterface);

Fixed of the above code.
$orderResultInterface = $this->getMockBuilder('Storm\Sales\Api\Data\OrderResultInterface')
    ->disableOriginalConstructor()
    ->getMock();
$orderInvoiceResultInterface = $this->getMockBuilder('Winz\Sales\Api\Data\OrderInvoiceResultInterface')
    ->disableOriginalConstructor()              
    ->setMethods(['setOrder', 'setInvoice', 'getOrder', 'getInvoice', ])
    ->getMock();      
$objectManagerInterface
    ->expects($this->any())
    ->method('create')
    ->withConsecutive(
            ['Storm\Sales\Api\Data\OrderResultInterface'],
            ['Storm\Sales\Api\Data\OrderInvoiceResultInterface']
    )
    ->willReturnOnConsecutiveCalls(
            $this->returnValue($orderResultInterface),
            $this->returnValue($orderInvoiceResultInterface)
    );


Sep 26, 2017

Magento2 - List of Validation Rules

List of form validation rules
jQuery rules:
required,
remote,
email,
url,
date,
dateISO,
number,
digits,
creditcard,
equalTo,
maxlength,
minlength,
rangelength,
range,
max,
min
Magento rules:
max-words
min-words
range-words
letters-with-basic-punc
alphanumeric
letters-only
no-whitespace
zip-range
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
stripped-min-length
email2
url2
credit-card-types
ipv4
ipv6
pattern
allow-container-className
validate-no-html-tags
validate-select
validate-no-empty
validate-alphanum-with-spaces
validate-data
validate-street
validate-phoneStrict
validate-phoneLax
validate-fax
validate-email
validate-emailSender
validate-password
validate-admin-password
validate-customer-password
validate-url
validate-clean-url
validate-xml-identifier
validate-ssn
validate-zip-us
validate-date-au
validate-currency-dollar
validate-not-negative-number
validate-zero-or-greater
validate-greater-than-zero
validate-css-length
validate-number
required-number
validate-number-range
validate-digits
validate-digits-range
validate-range
validate-alpha
validate-code
validate-alphanum
validate-date
validate-date-range
validate-cpassword
validate-identifier
validate-zip-international
validate-one-required
validate-state
required-file
validate-ajax-error
validate-optional-datetime
validate-required-datetime
validate-one-required-by-name
less-than-equals-to
greater-than-equals-to
validate-emails
validate-cc-type-select
validate-cc-number
validate-cc-type
validate-cc-exp
validate-cc-cvn
validate-cc-ukss
validate-length
required-entry
not-negative-amount
validate-per-page-value-list
validate-per-page-value
validate-new-password
required-if-not-specified
required-if-all-sku-empty-and-file-not-loaded
required-if-specified
required-number-if-specified
datetime-validation
required-text-swatch-entry
required-visual-swatch-entry
required-dropdown-attribute-entry
Validate-item-quantity
validate-grouped-qty
validate-one-checkbox-required-by-name
validate-date-between
validate-dob

Aug 15, 2017

Magento 2 - Best way to mass update attribute value of a product.

Here my code.
$productIds = [1,2,34]; // List of product Ids
$productAttribute = \Magento\Framework\App\ObjectManager::getInstance()
            ->create('Magento\Catalog\Model\ResourceModel\Product\Action');
$productAttribute->updateAttributes($productIds, 
['name' => 'New Name for all product'], // List of attribute you want to update NVP
$storeId
);

Idea gets from best-way-to-update-products-attribute-value

Jul 9, 2017

Laravel5 -> Creating/Understanding Custom Validation.

Main goal to create our own validation and set message associated to our validation.

*

Implented the validation rule

$RULES = ['name' => 'required|myrule'];
Vaidator::make($ARRAY_DATA, $RULES);

*

Create custom rule. In app/Providers/AppServiceProvider.php add code below on boot function.

//  Create  your custome valitor
Validator::extend('myrule', function($attr $value, $params) {
    return ((rand(10,100)%2) == 0); // Random return failed/Pass
},
"validation.myrule"
);

// Create the  message rule message.
Validator::replacer('myrule', function($msg, $attr, $rule, $params) {
    return trans($message, ['attribute'=> $attribute]);
});

*

Create the rule message. Add entry on resources/lang/en/validation.php.


return [

'myrule' => 'Your :attribute got error.',

'custom' => [
  //  Your also add here, to override the message above for the specific file.
  // This not need unless you want some validation on specific field.
  'fieldname' => [
     'rulename' => ' This just sample custom my rule message',
   ],

  'name' => [
     'myrule' => 'My custom :attribute message override.',
   ]

]
];

Jun 29, 2017

Magento2 - Resetting admin password.

Reseting password could get 3 possible way.

1. Run command in your server console.

MAGENTO_DIR/bin/magento admin:user:create \
--admin-user="ADMINUSERNAME" \
--admin-password="NEWPASSWORD" \
--admin-email="admin@example.com" \
--admin-firstname="Admin" --admin-lastname="Admin"

2. If you dont have access to the server, you could try updating via your database server.

UPDATE admin_user 
SET password = CONCAT(SHA2('xxxxxxxYourNewPassword', 256), ':xxxxxxx:1') 
WHERE username = 'admin';
NOTE: xxxxxx character sequence is a cryptographic salt.
it is saved in app\etc\env.php file
<?php
return array (
  ...
  'crypt' => 
  array (
    'key' => '525701df74e6cba74d5e9a1bb3d935ad', //cryptographic salt
  ),
  ...

3. Use the Forgot Password.

May 31, 2017

Laravel5 - Working on multiple DB.

Some reasons you need multiple DB when you making test migration on current working application.
Like my case, you are currently working on postgresql which the old DB in in mysql. Which tester the current posgre DB. I cant made that DB as my migration destination. This I why I need multiple DB configuration.

Here simple thing I did.

* Configure database setting(config/database.php) to defined mutiple DB.
return [
    'default' => env('DB_CONNECTION', 'pgsql'),
    'fetch' => PDO::FETCH_ASSOC, 
    'connections' => [
        'pgsql' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST'),
            'database' => env('DB_DATABASE'),
            'username' => env('DB_USERNAME'),
            'password' => env('DB_PASSWORD'),
            'charset'  => env('DB_CHARSET', 'utf8'),
            'prefix'   => env('DB_PREFIX', ''),
            'schema'   => env('DB_SCHEMA', 'core'),
        ],
        
        /*
         * START -
         * Migration Tesd DB
         */
        'migration' => [
            // My Postgre DB Destination
            'driver' => 'pgsql',
            'host' => 'localhost'
            'database' => 'dest_db',
            'username' => 'myuser,
            'password' => 'MyPaswordd',
            'charset'  => env('DB_CHARSET', 'utf8'),
            'prefix'   => env('DB_PREFIX', ''),
            'schema'   => env('DB_SCHEMA', 'core'),
        ],
        'mysql' => [
            // Source Mysql DB Data.
            'driver'    => 'mysql',
            'host'      => '192.168.101.17',
            'port'      => 3306,
            'database'  => 'src_db',
            'username'  => 'myuser',
            'password'  => 'mypassword',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            //'timezone'  => env('DB_TIMEZONE', '+00:00'),
            'strict'    => env('DB_STRICT_MODE', false),
        ],
    ],
];


While Working on migration script. I learn to use the Console feature of laravel.

$users = DB::connection('mysql')
    ->select('SELECT * FROM users '
        . 'limit 10' // For testing I put limit
    );

foreach($users as $user){
    // Create as object since "setConnection" none static
    $myuser = new \App\Model\App\Users();
    // Store the user to PSQL.
    // Assume the old and new table are same field names
    $myuser->setConnection('migration')
            ->store($user);

}

Feb 22, 2017

Laravel5 - How to log sql query?

Simple way, try to add code below on you route.

\Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
    \Log::debug($query->sql);
    //var_dump($query->bindings);
    //var_dump($query->time);
});


Working on 5.3