Categories
BEST PHP CODE PHPUnit

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

 

Categories
General

Delete Git History

#1 – Terminal

Git Rebase <commit-hash>

#2 – from vi/vim do the following changes – replace ‘pick’ by ‘drop’

#3 – Commit Current Change

git commit –allow-empty

#4 – Continue Rebase for cofirmation of what you want to see

git rebase –continue

#5 – Command line – Push to your repository

git push -f

#6 – Final Screen ‘bbb’ removed

 

 

Categories
BEST PHP CODE

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

Categories
General

David Raleche Expertise

David Raleche Expertise

  • The Lead Software Engineer conceives, designs, develops, tests, and implements software fixes, enhancements, components, and/or new software systems and applications with a high level of complexity, where a project encompasses multiple components.
  • The Lead Software Engineer applies practical knowledge of technologies and concepts to lead software engineering teams on large projects, providing technical guidance and oversight and acting as a point of escalation and technical expert.
  • The Lead Software Engineer has accountability for planning, structuring, and leading the execution of development projects.

Experience

  • Owns and leads large development projects and teams where a project comprises multiple components; oversees project teams as required.
  • Leads the development of highly innovative, large, software solutions that meet specifications and significantly impact future developments.
  • Conceives and leads the execution of major software development projects and major fixes using new or existing technologies.
  • Leads the development of specifications for major software development projects.
  • Reviews or writes code
  • Leads programming and testing and debugging of major software development projects.
  • Creates protocols, documentation and tools for the installation and maintenance of major software projects.
  • Conceives and sets the design and direction for major software development projects.
  • Leads the design of components of major software development projects, developing specifications for each.
  • Designs, develops, manages, creates and maintains the technical components and templates for front end screens for clients.
  • Strong understanding of the front-end technology stack; able to code against front-end and lead end-to-end troubleshooting.
  • Interacts and coordinates deliverables with other technical groups in the organization.
  • Executes assigned component level projects using new or existing technologies.
  • Designs and develops specifications for assigned projects.
  • Reviews or troubleshoots and performs testing.
  • Participates in conceiving and setting the direction for development projects.
  • Influences the work of team members, other teams, and assigned projects through decisions and actions.
  • Designs the component tasks of assigned projects, developing specifications for each.
  • Serves as a high-level technical resource and “go-to” person for less experienced developers and leadership, providing technical guidance and oversight.
  • Recommends improvements to processes, technology, and interfaces that improve the effectiveness of the team.
  • Responsible for coordinating the workload across team members.
Categories
BEST PHP CODE Security

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
Categories
BEST PHP CODE

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);
}
Categories
AWS AWS SQS BEST PHP CODE

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);
    }

 

 

Categories
Continuous Integration/Development Programming Web API

How to step by step implement Continuous Integration and Continuous Development in your software team ?

Fast development and Integration according to David Raleche – Process

 

 

 

QA

  • Introducing new bugs after making a change (No proper regression test)
  • Increase Automation overall
  • Lack of transparency
  • Improve quality and testability
  • No Proper Api documentation (Swagger)

Developers

  • Duplicate code throughout the program
  • Reading or writing code which is difficult to understand (PSR-2)
  • No Peer Programming (Code Review) in place (Pull Request)

 

  • CLEAN CODE

 

  • DRY do not repeat yourself
  • KISS – Keep it Stupid Simple
  • PSR-2 Code Styling
  • PSR-3 Log for debug purposes
  • PSR-4 Comment Code Properly
  • Function no exceeding 40 lines

 

  • No ERRORS

 

  • PHP Code
    • No Errors
    • No Warnings
    • No Notices
  • Unit Testing – 2 per api calls

 

  • CREATE Functional API Test

 

    • 3 positive tests
    • 3 negatives

 

 

  • Final API Documentation (swagger)

 

 

  • Check PHP logs (Nagios)
    • PHP Code
      • No Errors
      • No Warnings
      • No Notices

 

  • Execute Regression Testing

  • Make sure unit testing reach out full Code coverage
Categories
General

what is >/dev/null 2>&1

> is for redirect

/dev/null is a black hole where any data sent, will be discarded

2 is the file descriptor for Standard Error

> is for redirect

& is the symbol for file descriptor (without it, the following 1 would be considered a filename)

1 is the file descriptor for Standard Out

Therefore >/dev/null 2>&1 is redirect the output of your program to /dev/null. Include both the Standard Error and Standard Out.

Much more information is available at The Linux Documentation Project’s I/O Redirection page.

cron will only email you if there is some output from you job. With everything redirected to null, there is no output and hence cron will not email you.

Categories
BEST PHP CODE

List GIT conflicted files

git diff --name-only --diff-filter=U