Categories
General

PHP API Architecture

 

 

david-raleche-php-api-architecture-bundle
david-raleche-php-api-architecture-bundle

PHP API – Bundle composition

  • controllers
  • services
  • models
  • repositories
  • tests (unit test)

 

Categories
AWS AWS SQS javascript

SOLUTION – POST API CALL in AWS SQS-LAMBDA – NODEJS – Javascript

If you have been struggling in amazon aws with the combo Lambda-SQS NodeJS fixing following type of errors :

read ECONNRESET at TLSWrap.onStreamRead

Error: read ECONNRESET at TLSWrap.onStreamRead

 

ERROR Uncaught Exception {“errorType”:”Error”,”errorMessage”:”getaddrinfo ENOTFOUND https://xxxx.xxxxxr.com https://xxxxx.xxxxx.com:443″,”code”:”ENOTFOUND”,”stack”:[“Error: getaddrinfo ENOTFOUND

 

ERROR Invoke Error {“errorType”:”TypeError [ERR_INVALID_ARG_TYPE]”,”errorMessage”:”The first argument must be one

Here is the solution

exports.handler = async (event) => {
     try {
         const res = await axios.post('https://davidraleche.com/v1/test',JSON.stringify({}), {
         headers: {
             'Content-Type': 'application/json'
         }})
         console.log(res)
         return {
             statusCode: 200,
             body: res.data
         }
     } catch (e) {
         console.log(e)
         return {
             statusCode: 400,
             body: JSON.stringify(e)
         }
     }
};

 

Categories
Technical

About Me

Developers spend considerable time configuring their work environment. This is an exhausting task and it is tiring. Software engineering is Joy when we can develop and think about logic and Speed performance. This is the whole purpose of this blog !

I am from France (Paris area) and I now live in Los Angeles where the scenery is gorgeous and the weather is clement and welcoming. See some beautiful pictures on the following link  instagram.com/dolosangeles

Los Angeles

have a look to business. directory of Los Angeles
losangeles.raleche.com

New York City

I have worked many years in New York City in the IT and gaming industry. At first I have worked as an IT consultant for diverse french luxury companies. I was leading projects onsite and managing a team of developers based in Philippines. It provided me great experience in managing team overseas. Afterward I worked for a well-known french real estate agency focusing on short-term rental until the arrival of the mega-monster company airBnb who took over the entire industry such as a tsunami. Thereafter, I spent many years working in the gaming industry where I developed and pioneer innovative social gaming technics with Facebook at their headquarter Menlo Park

see more pictures here https://raleche.blogspot.com/p/my-past-experience-high5games-new-york.htmlSee below the view from my ex-office the world trade center known as the freedom tower today in New York City while working for high 5 games

Professional Career

I am specialized in LAMP stack environments (Linux, Apache, MYSQL, PHP) I have more than 15 years experience with PHP. 

LinkedIn
linkedin.com/in/davidraleche/

Stackoverflow
https://stackoverflow.com/users/7782346/david-raleche

I have developed APIs, backend websites and frontend websites, I have managed teams and implemented complex automated solutions throughout my career I have experienced new programming environment in the cloud such as AWS (NodeJs, Lambda, SQS, SNS)
I am a technologist enthusiast and share my findings via different social media platforms

Packagist
packagist.org/packages/yana/dr

Blogs
https://medium.com/@davidraleche

Twitter
https://twitter.com/DavidRaleche

EDUCATION


Stevens Institute of Technology, Hoboken USA
Master of Information System – Dec 2008

Epitech Graduate School of Digital Innovation, Paris France
Master of Computer Science – Dec 2007


Hobbies


HOA President – 2016 – present
Home Owner Association

Google Analytics/Adwords Certified – 2018

Languages

English

French

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