Saturday, June 3, 2017

PHP Tag Lib: PHP Custom Tag Library (TagLib)

We use tag in your HTML page such as "DIV", "H2", "P" etc in every moment in our life. Who used Grail's or Spring MVC he has knowledge on custom tag library. We can also use custom tag lib in PHP project. Below is a example of PHP custom tag lib usage:

<tglib:upper>Goes to upper</tglib:upper>

To drive output of this custom tag in PHP, you have to download and include tag lib library first from below link:

drive.google.com/PHP Tag Lib: PHP Custom Tag Library (TagLib)

We used tglib:upper in above script, so we have to make a directory in "TagLib" directory named "upper" with a function named "tglib___upper" that support $tag parameter. With will supply tag name as well as any attributes in that tag. 

Below is a sample example of "upper" tag:

function tglib___upper($tag)
{
    return strtoupper($tag['content']);
}


$tag["content"] contains body parts of the tag.

If you download and execute "tag1.php" file, below output will be generated:





jQuery Script: Remove next element by class name

Its very easy to remove next element by checking class is matches or not. You can also remove previous element as well as next element.

$(".base").prev(".search").remove();

<script src="3.2.1/jquery.min.js"></script>

<div class="base">ELEMENT 1</div>
<div class="will_not_remove">ELEMENT WILL NOT REMOVE</div>
<div class="remove">HAS CLASS "REMOVE" BUT WILL NOT REMOVE</div>
<div class="base">ELEMENT 2</div>
<div class="remove">ELEMENT WILL REMOVE</div>

<script type="text/javascript">
    $(".base").next(".remove").remove();
</script>



Sunday, May 28, 2017

PHP Script: Call Method Dynamically

PHP Script: Call Method Dynamically. Below is PHP Script which describes the full process:

<?php
$fnc = "canCall";
if (!is_callable($fnc)) {
    echo "Cant call method: $fnc <BR>";
} else {
    echo "Return from method $fnc: " . $fnc(15) . "<BR>";
}

$fnc = "canCall2";
if (!is_callable($fnc)) {
    echo "Cant call method: $fnc <BR>";
} else {
    echo "Return from method $fnc: " . $fnc(15) . "<BR>";
}

function canCall($a = 10)
{
    return $a * 5;
}

$caller_class = new CallerClass();
$caller_class->check();

class CallerClass
{
    private $for_method1 = 10;

    public function check()
    {
        $fnc = "method1";
        if (!is_callable(array(&$this, $fnc))) {
            echo "$fnc is not callable function";
        } else {
            $this->{"for_method1"} = 20;
            echo "Return from $fnc:" . $this->{$fnc}() . "<BR>";
        }

        $fnc = "method2";
        if (!is_callable(array(&$this, $fnc))) {
            echo "$fnc is not callable function";
        } else {
            echo "Return from $fnc:" . $this->{$fnc}() . "<BR>";
        }
    }

    public function method1()
    {
        return "From method 1 <$this->for_method1>";
    }
}

?>


Which will output as below:

Return from method canCall: 75
Cant call method: canCall2 
Return from method1:From method 1 <20>
method2 is not callable function

PHP Script: Define Variable Dynamically

PHP Script: Define Variable Dynamically. Its easy:

${"variable"} = "Variable defined dynamically";

echo $variable;


Will output:

Variable defined dynamically

And in class file (both static and instance scope):

SomeClass::test();
SomeClass::test2();

$class = new SomeClass();
$class->test3();

class SomeClass {
    static $xxx = null;

    static function test() {
        self::${"xxx"} = "Value";
    }

    static function test2() {
        echo self::${"xxx"} . "::" . self::$xxx;
    }

    function test3() {
        $this->{"yyyy"} = "Value of YYYY";
        echo "<BR>" . $this->yyyy;
    }
}

How to PHP call another page and get output as variable?

How to PHP call another page and get output as variable? it's easy. We can do it in two way. First way is processing via ob_... and second way is get content in a variable and execute eval function. 

Below is a PHP Script which will describes both way:


<?php
ob_start();
${"variable"} = array("as_array" => "Test variable value in array #Method 1");
require 'content.txt';
$output = ob_get_clean();
echo $output;

${"variable"} = array("as_array" => "Test variable value in array #Method 2");
$file = file_get_contents('content.txt');
$content = eval("?>$file");
echo $content;


Content of "content.txt" file below:

<div style="margin: 10px; border: 1px solid red; padding: 10px;">
    <h3>HI, Time = <?= date("d/m/Y h:i A") ?></h3>
    <h4><?= $variable["as_array"] ?></h4>
    <table>
        <tr>
            <td>TABLE > TR > TD</td>
        </tr>
    </table>
</div>


And output of above PHP Script below:


HI, Time = 28/05/2017 02:56 PM

Test variable value in array #Method 1

TABLE > TR > TD

HI, Time = 28/05/2017 02:56 PM

Test variable value in array #Method 2

TABLE > TR > TD

Saturday, May 27, 2017

Git Merge Working Branch With Remove Branch

At first you nee to update your local branch using below command. It may better your have no local changes.

git pull

Then execute following command to update current branch with specific remote branch:

git merge remotes/origin/remote_branch

Sometimes it may prompt the following dialog:



Then you have to follow the below steps:

1. Press `i` to enable edit mode
2. Use down cursor go to the last line and introduce new line
3. Put some comments
4. Press `Esc` then `:wq!` and hit Enter key
5. You are done with merge
6. And finally execute "git push" to push changes

Sometime it may told you that some conflict occurred with the list of files, then you need to merge them before do merge.

After conflict occurred executed command "git merge --abort" to abort current merge request and then merge conflict before try again merge.

The simplest solution is fetch conflict file from the branch from where you want to merge using below command:

git checkout origin/branch_name app/directory/file.name

and push all files and then try again, i think it helps.

Sometimes it may need to stash your local changes before execute "git merge ..." command:

git stash

And after execute "git merge ..." execute below command to unstash changes:

git stash apply stash@{0}

To reset your current working branch:

git reset --hard (will move to previous commit)

And finally if you want to clear all untracked files execute:

git clean -fd


Stripe Payment API: Create Charge Or Payment

You need a Token (Saved credit card instance) to create a Payment which is known as Charge in Stripe API. Creating Charge in Stripe is equal to creating a Payment. 

Payment API documentation:
https://stripe.com/docs/api#charges

<?php
function createCharge()
{
    $token = CreateToken::create();

    if ($token["code"] != 200) {
        StripeCharge::prettyPrint($token["response"]);
        exit;
    }

    $params = array(
        "amount" => "200",
        "currency" => "aud",
        "source" => $token["response"]->id,
        "description" => "Some description against charge/payment"
    );
    $create = StripeCharge::create($params);
    StripeCharge::prettyPrint($create);
}
createCharge();

class StripeCharge {
    private static $key = "sk_test_...";

    static function create($params)
    {
        $url = "https://api.stripe.com/v1/charges";

        $headers[] = "Authorization: Bearer " . self::$key;
        $headers[] = "Content-Type: application/x-www-form-urlencoded";

        return makeCurlCall($url, "POST", null, $params, $headers);
    }

    static function prettyPrint($data)
    {
        echo "<pre>";
        print_r($data);
        echo "</pre>";
    }
}

Output below:



Array
(
    [code] => 200
    [response] => stdClass Object
        (
            [id] => ch_1ANxxAFIwfarG3vBDqR8ROkg
            [object] => charge
            [amount] => 200
            [amount_refunded] => 0
            [application] =>
            [application_fee] =>
            [balance_transaction] => txn_1ANxxAFIwfarG3vB3wrLUKgn
            [captured] => 1
            [created] => 1495864748
            [currency] => aud
            [customer] =>
            [description] => Some description against charge/payment
            [destination] =>
            [dispute] =>
            [failure_code] =>
            [failure_message] =>
            [fraud_details] => stdClass Object
                (
                )

            [invoice] =>
            [livemode] =>
            [metadata] => stdClass Object
                (
                )

            [on_behalf_of] =>
            [order] =>
            [outcome] => stdClass Object
                (
                    [network_status] => approved_by_network
                    [reason] =>
                    [risk_level] => normal
                    [seller_message] => Payment complete.
                    [type] => authorized
                )

            [paid] => 1
            [receipt_email] =>
            [receipt_number] =>
            [refunded] =>
            [refunds] => stdClass Object
                (
                    [object] => list
                    [data] => Array
                        (
                        )

                    [has_more] =>
                    [total_count] => 0
                    [url] => /v1/charges/ch_1ANxxAFIwfarG3vBDqR8ROkg/refunds
                )

            [review] =>
            [shipping] =>
            [source] => stdClass Object
                (
                    [id] => card_1ANxx8FIwfarG3vBa0fmLGhT
                    [object] => card
                    [address_city] =>
                    [address_country] =>
                    [address_line1] =>
                    [address_line1_check] =>
                    [address_line2] =>
                    [address_state] =>
                    [address_zip] =>
                    [address_zip_check] =>
                    [brand] => Visa
                    [country] => US
                    [customer] =>
                    [cvc_check] => pass
                    [dynamic_last4] =>
                    [exp_month] => 12
                    [exp_year] => 2019
                    [fingerprint] => CjZNbbCtG5QSnuIS
                    [funding] => credit
                    [last4] => 4242
                    [metadata] => stdClass Object
                        (
                        )

                    [name] => Card Name
                    [tokenization_method] =>
                )

            [source_transfer] =>
            [statement_descriptor] =>
            [status] => succeeded
            [transfer_group] =>
        )

)