PHP DocBlock

/**
 * Returns a list of XXXXXXX
 *
 * @param string $route_group_uuid
 *
 * @return Array $listCarrierRoute
 *
 * @throws \Exception
 *
 * @version 05-05-2020
 * @author David Raleche <david@raleche.com>
 * @reference JIRA Ticket PMM2-862 Create route groups XXXXX
 */

PHP 7.4 – Null Coalescing Assignment Operator

Null Coalescing Assignment Operator

In the long run, this code could be a bit difficult to maintain. So, aiming to help developers to write more intuitive code, this RFC proposes the introduction of the null coalescing assignment operator (??=). So, instead of writing the previous code, we could write the following:

$this->request->data['comments']['user_id'] ??= ‘value’;

New Features php-7.4

source : https://raw.githubusercontent.com/php/php-src/php-7.4.0beta4/UPGRADING

========================================
2. New Features
========================================

- Core:
  . Added support for typed properties. For example:

        class User {
            public int $id;
            public string $name;
        }

    This will enforce that $user->id can only be assigned integers and
    $user->name can only be assigned strings. For more information see the
    RFC: https://wiki.php.net/rfc/typed_properties_v2



  . Added support for coalesce assign (??=) operator. For example:

        $array['key'] ??= computeDefault();
        // is roughly equivalent to
        if (!isset($array['key'])) {
            $array['key'] = computeDefault();
        }

    RFC: https://wiki.php.net/rfc/null_coalesce_equal_operator

  . Added support for unpacking inside arrays. For example:

        $arr1 = [3, 4];
        $arr2 = [1, 2, ...$arr1, 5];
        // $arr2 == [1, 2, 3, 4, 5]

    RFC: https://wiki.php.net/rfc/spread_operator_for_array

.php.net/rfc/tostring_exceptions

PHPUnit (truncated…) – SOLUTION

Hi Team,

If you experienced the difficult task to debug through PhpUnit find here a global solution !

The exception caught is related to the guzzle version

The solution is a try-catch around your phpunit test and expose the GuzzleException $e

 $client = new GuzzleHttp\Client(['base_uri' => 'https://foo.com/api/']);

try {

       $response = $client->request('GET','/v1/testYourEndpoint');

} catch (\GuzzleHttp\Exception\ClientErrorResponseException  $e) {
    var_dump($e->getResponse()->getBody()->getContents());

} catch (\GuzzleHttp\Exception\RequestException $e) {
    var_dump($e->getResponse()->getBody()->getContents());

} catch (\GuzzleHttp\Exception\ClientException  $e) {
    var_dump($e->getResponse()->getBody()->getContents());
}

Enjoy !
David Raleche

 

GIT HELPER DAVID RALECHE

SYNC GIT

git remote update

git fetch Downloads the latest from remote without trying to merge or rebase anything.

git fetch -- all

REMOVE untracked files

git clean -f -d

Rename Git Commit

git commit -amend

RESET BRANCH/FILE

git reset --hard origin/master — force discard local changes

git reset --hard origin/<davidBranch_name> — force discard local changes

git checkout -f <localfile> — force discard local changes

COMMIT

git commit -m ‘My commit David Raleche’

remove git add

git reset HEAD -file-

PUSH

git push origin <davidBranch>

CONFLICTED FILES

git diff --name-only --diff-filter=U GIT ADD git add <file> git commit -m “message of your commit” git push origin

GIT RESET ADD

git reset <file> git reset

(VERY DANGEROUS) REMOVING LAST COMMIT (VERY DANGEROUS)

git reset --soft HEAD~1

git reset --hard HEAD^

(VERY DANGEROUS)

GIT CHECKOUT SOMEONE ELSE REPO

git checkout --track origin/ECOM-307

Centos scan open ports TCP

 

Nmap is a great port scanner, but sometimes you want something more authoritative. You can ask the kernel what processes have which ports open by using the netstat utility:

  • -t TCP only
  • -l Listening ports only
  • -n Don’t look up service and host names, just display numbers
  • -p Show process information (requires root privilege)

 

netstat -tlnp

How to generate Salt for password encryption

Generate Password with Salt Technic

public function generateSalt(int $size = null) : string
{
if ($size === null) {
$size = 22;
}

return $this->salt = bin2hex(random_bytes($size));
}

/**
* Generate Token / HashToken
*
* @parameter array $salt
*
* @return string
*/
public function generateToken(string $salt): string
{
if ($salt === null) {
$salt = $this->generateSalt();
}

$options = [ 'cost' => 12, 'salt' => $salt ];
$passwordHash = password_hash(
$password,
PASSWORD_BCRYPT,
$options
);

return base64_encode($passwordHash);
}

 

Verify Password Validity

if (password_verify($queryResult[0]['user_uuid'].$queryResult[0]['organization_uuid'], base64_decode($this->session->token))) {
    // Correct password
} else {
    $this->issue('Token not valid :'.$this->session->token);
}

AWS SQS Library

Image result for aws

Interface Contract

<?php

namespace David\App\Models;

interface Queue
{
    public function push(array $message);
    public function pop() : array;
    public function flush(string $queueUrl);
    public function process();
}

 

QueueService Class

<?php

namespace App\Core\Services;

use App\Core\Prelude;
use Aws\Sqs\SqsClient;
use Mapi\App\Models\Queue;

/**
 * Class QueueService
 *
 * @package App\Core\Services
 */
class QueueService extends \App\Core\Classes\Service implements Queue
{
    /**
     * QueueConfigs
     *
     * @var bool
     */
    private $queueConfigs = false;
    /**
     * DbConnections
     *
     * @var bool
     */
    private $dbConnections = false;
    /**
     * SqsClient
     *
     * @var SqsClient|bool
     */
    private $sqsClient  = false;

    /**
     * GetSqsClient
     *
     * @return SqsClient|bool|static
     */
    public function getSqsClient()
    {
        return $this->sqsClient;
    }

    /**
     * SetSqsClient
     *
     * @param SqsClient|bool|static $sqsClient
     */
    public function setSqsClient($sqsClient)
    {
        $this->sqsClient = $sqsClient;
    }

    /**
     * StorageService constructor.
     */
    public function __construct($queue_name, Prelude $prelude)
    {
        if ($queue_name === null) {
            die(
                'QueueService::constructor queue_name does not exist');
        }
        $this->prelude = $prelude;
        $this->queues = $this->queueConfigs()['queues'];
        $this->selectedQueue =  $this->queues[$queue_name];
        $this->queueUrl = $this->selectedQueue['queue_url'] ;
        $this->sqsCredentials = array(
            'region' => $this->selectedQueue['region'],
            'version' => $this->selectedQueue['version'],
            'credentials' => array(
                'key' => $this->selectedQueue['key'],
                'secret' =>$this->selectedQueue['secret'],
            ),
        );

        $this->sqsClient = $this->queueConnect($queue_name);
    }

    /**
     * Storage Configs
     *
     * @return bool|mixed
     */
    private function queueConfigs()
    {
        if ($this->queueConfigs === false) {
            $this->queueConfigs = yaml_parse_file(__DIR__.'/../../config/storage.yaml');
        }

        return $this->queueConfigs;
    }

    /**
     * Queue connection
     *
     * @param string $schema
     * @param bool $allowShared
     */
    public function queueConnect()
    {
        try {
            // Instantiate the client
            $sqsClient = SqsClient::factory($this->sqsCredentials);
        } catch (Exception $e) {
            die('Error Connecting to the Queue '.$e->getMessage());
        }

        return $sqsClient;
    }

    /**
     * Push
     *
     * @param string $jsonMessage
     *
     * @return bool
     */
    public function push(array $params) : bool
    {
        try {
            // Send the message
            $this->sqsClient->sendMessage(
                $params
            );
        } catch (Exception $e) {
            die('Error sending message to queue '.$e->getMessage());
            return false;
        }
        return true;
    }

    public function deleteMessage($result)
    {
        $this->sqsClient->deleteMessage(
            [
                'QueueUrl' => $this->queueUrl, // REQUIRED
                'ReceiptHandle' => $result->get('Messages')[0]['ReceiptHandle'] // REQUIRED
            ]
        );
    }

    /**
     * Pop Message
     *
     * @return array
     */
    public function pop() : array
    {
        $resultMessage = array();
        try {
            $result = $this->sqsClient->receiveMessage(
                array(
                    'AttributeNames' => ['SentTimestamp'],
                    'MaxNumberOfMessages' => 1,
                    'MessageAttributeNames' => ['All'],
                    'QueueUrl' => $this->queueUrl,
                    'WaitTimeSeconds' => 0,
                )
            );
            //Logging Pending Queue Messages
            $this->prelude->log->debug('QueueService:pop COUNT MESSAGES '
                    .count($result->getPath('Messages')));

            if (is_array($result->get('Messages'))) {
                if (count($result->get('Messages')) > 0) {
//                    $this->prelude->log->debug('QueueService:pop'
//                        .json_encode($result->get('Messages')));

                    $status = true;
                    $resultMessage = $result->get('Messages')[0]['Body'];
                    //Delete Message
                    $this->deleteMessage($result);
                }
            } else {
                $status = false;
                $resultMessage = "No messages in queue. \n";
            }
        } catch (Exception $e) {
            die(' message to queue '.$e->getMessage());
        }
        // Add Debugging SQS QUEUE
        $this->prelude->log->debug('WORKER BODY MESSAGE '.$resultMessage);
        return array('status' => $status, 'result' => $resultMessage);
    }