소스 검색

Merge pull request #5 from ixudra/feature/builder

Added fluent request builder for easier and more intuitive coding
Jan Oris 9 년 전
부모
커밋
4799f5dff0
5개의 변경된 파일330개의 추가작업 그리고 153개의 파일을 삭제
  1. 88 39
      README.md
  2. 1 1
      composer.json
  3. 234 0
      src/Ixudra/Curl/Builder.php
  4. 0 75
      src/Ixudra/Curl/Curl.php
  5. 7 38
      src/Ixudra/Curl/CurlService.php

+ 88 - 39
README.md

@@ -1,12 +1,13 @@
 ixudra/curl
 ================
 
-Custom PHP curl library for the Laravel 4 and 5 framework - developed by [Ixudra](http://ixudra.be).
+Custom PHP cURL library for the Laravel 4 or 5 framework - developed by [Ixudra](http://ixudra.be).
 
 This package can be used by anyone at any given time, but keep in mind that it is optimized for my personal custom workflow. It may not suit your project perfectly and modifications may be in order.
 
 
 
+
 ## Installation
 
 Pull this package in through Composer.
@@ -15,12 +16,14 @@ Pull this package in through Composer.
 
     {
         "require": {
-            "ixudra/curl": "5.*"
+            "ixudra/curl": "6.*"
         }
     }
 
 ```
-### Laravel 4.* Integration
+
+
+### Laravel 5.* Integration
 
 Add the service provider to your `config/app.php` file:
 
@@ -29,7 +32,7 @@ Add the service provider to your `config/app.php` file:
     'providers'     => array(
 
         //...
-        'Ixudra\Curl\CurlServiceProvider',
+        Ixudra\Curl\CurlServiceProvider::class,
 
     ),
 
@@ -42,98 +45,144 @@ Add the facade to your `config/app.php` file:
     'facades'       => array(
 
         //...
-        'Curl'          => 'Ixudra\Curl\Facades\Curl',
+        'Curl'          => Ixudra\Curl\Facades\Curl::class,
 
     ),
 
 ```
 
-### Laravel 5.* Integration
 
-Add the service provider to your `config/app.php` file:
+### Laravel 4.* Integration
+
+Add the service provider to your `app/config/app.php` file:
 
 ```php
 
     'providers'     => array(
 
         //...
-        Ixudra\Curl\CurlServiceProvider::class,
+        'Ixudra\Curl\CurlServiceProvider',
 
     ),
 
 ```
 
-Add the facade to your `config/app.php` file:
+Add the facade to your `app/config/app.php` file:
 
 ```php
 
     'facades'       => array(
 
         //...
-        'Curl'          => Ixudra\Curl\Facades\Curl::class,
+        'Curl'          => 'Ixudra\Curl\Facades\Curl',
 
     ),
 
 ```
 
+### Integration without Laravel
+
+Create a new instance of the `CurlService` where you would like to use the package:
+
+```php
+
+    $curlService = new \Ixudra\Curl\CurlService();
+
+```
+
+
+
 
 ## Usage
 
-### GET requests
+### Laravel usage
+
+The package provides an easy interface for sending cURL requests from your application. The package provides a fluent 
+interface similar the Laravel query builder to easily configure the request. There are several utility methods that allow
+you to easily add certain options to the request. If no utility method applies, you can also use the general `withOption`
+method.
 
-The package provides an easy interface for sending CURL requests from your application. Optionally, you can also
-include several `GET` parameters that will automatically be added to the base URL by the package automatically. Lastly,
-the package also has a parameter that allows you to easily mark a request as a JSON requests. The package will
-automatically handle the conversion from and to JSON to PHP if needed. The default value of this parameter is `false`.
-The last parameter can be used to pass additional CURL parameters to the request:
+In order to send the request, you need to use the method which matches the HTTP method of the request you are trying to
+send. Currently, only the `GET` and `POST` method are supported. `PUT` and `DELETE` will be added in the near future.
 
 ```php
 
     // Send a GET request to: http://www.foo.com/bar
-    Curl::get('http://www.foo.com/bar');
+    Curl::to('http://www.foo.com/bar')
+        ->get();
 
     // Send a GET request to: http://www.foo.com/bar?foz=baz
-    Curl::get('http://www.foo.com/bar', array('foz' => 'baz'));
+    Curl::to('http://www.foo.com/bar')
+        ->withData( array( 'foz' => 'baz' ) )
+        ->get();
 
     // Send a GET request to: http://www.foo.com/bar?foz=baz using JSON
-    Curl::get('http://www.foo.com/bar', array('foz' => 'baz'), true);
+    Curl::to('http://www.foo.com/bar')
+        ->withData( array( 'foz' => 'baz' ) )
+        ->asJson()
+        ->get();
 
     // Send a GET request to: http://www.foo.com/bar?foz=baz using JSON over SSL
-    Curl::get('http://www.foo.com/bar', array('foz' => 'baz'), true, array('SSL_VERIFYPEER' => false));
+    Curl::to('http://www.foo.com/bar')
+        ->withData( array( 'foz' => 'baz' ) )
+        ->withOption('SSL_VERIFYPEER', false)
+        ->get();
+
+    // Send a POST request to: http://www.foo.com/bar
+    Curl::to('http://www.foo.com/bar')
+        ->post();
+
+    // Send a POST request to: http://www.foo.com/bar
+    Curl::to('http://www.foo.com/bar')
+        ->withData( array( 'foz' => 'baz' ) )
+        ->post();
+
+    // Send a POST request to: http://www.foo.com/bar with arguments 'foz' = 'baz' using JSON
+    Curl::to('http://www.foo.com/bar')
+        ->withData( array( 'foz' => 'baz' ) )
+        ->asJson()
+        ->post();
+
+    // Send a POST request to: http://www.foo.com/bar with arguments 'foz' = 'baz' using JSON over SSL
+    Curl::to('http://www.foo.com/bar')
+        ->withData( array( 'foz' => 'baz' ) )
+        ->withOption('SSL_VERIFYPEER', false)
+        ->post();
 
 ```
 
-The package will automatically prepend the options with the `CURLOPT_` prefix. It is worth noting that the package does
-not perform any validation on the CURL options. Additional information about available CURL options can be found
+The package will automatically prepend the options with the `CURLOPT_` prefix. It is worth noting that the package does 
+not perform any validation on the cURL options. Additional information about available cURL options can be found
 [here](http://php.net/manual/en/function.curl-setopt.php).
 
 
+### Usage without Laravel
 
-### POST requests
-
-The package also allows you to send `POST` requests for your application. The first and second parameter are
-identical to the `Curl::get()` method. The `POST` parameters can be passed on as the third parameter. The fourth
-parameter can be used to mark the request as a JSON requests. The package will automatically handle the conversion
-from and to JSON to PHP is needed. The default value of this parameter is `false`. The last parameter can be used to
-pass additional CURL parameters to the request:
+Usage without Laravel is identical to usage described previously. The only difference is that you will not be able to 
+use the facades to access the `CurlService`.
 
 ```php
 
-    // Send a POST request to: http://www.foo.com/bar with arguments 'fow' = 'baw'
-    Curl::post('http://www.foo.com/bar', array(), array('fow' => 'baw'));
+    $curlService = new \Ixudra\Curl\CurlService();
+
+    // Send a GET request to: http://www.foo.com/bar
+    $curlService->to('http://www.foo.com/bar')
+        ->get();
+        
+    // Send a POST request to: http://www.foo.com/bar
+    $curlService->to('http://www.foo.com/bar')
+        ->post();
+
+```
 
-    // Send a POST request to: http://www.foo.com/bar?foz=baz with arguments 'fow' = 'baw'
-    Curl::post('http://www.foo.com/bar', array('foz' => 'baz'), array('fow' => 'baw'));
 
-    // Send a POST request to: http://www.foo.com/bar?foz=baz with arguments 'fow' = 'baw' using JSON
-    Curl::post('http://www.foo.com/bar', array('foz' => 'baz'), array('fow' => 'baw'), true);
 
-    // Send a POST request to: http://www.foo.com/bar?foz=baz with arguments 'fow' = 'baw' using JSON over SSL
-    Curl::post('http://www.foo.com/bar', array('foz' => 'baz'), array('fow' => 'baw'), true, array('SSL_VERIFYPEER' => false));
 
-```
+## Planning
 
-That's all there is to it! Have fun!
+ - Add `PUT` and `DELETE` method
+ - Add additional utility methods for other cURL options
+ - Add contract to allow different HTTP providers such as Guzzle
 
 
 

+ 1 - 1
composer.json

@@ -1,7 +1,7 @@
 {
     "name": "ixudra/curl",
     "description": "Custom PHP Curl library for the Laravel 5 framework - developed by Ixudra",
-    "version": "5.1.0",
+    "version": "6.0.0",
     "keywords": ["Ixudra", "Laravel", "Curl"],
     "homepage": "http://ixudra.be",
     "license": "MIT",

+ 234 - 0
src/Ixudra/Curl/Builder.php

@@ -0,0 +1,234 @@
+<?php namespace Ixudra\Curl;
+
+
+class Builder {
+
+    protected $curlObject = null;
+
+    protected $curlOptions = array(
+        'RETURN_TRANSFER'       => true,
+        'FAIL_ON_ERROR'         => true,
+        'FOLLOW_LOCATION'       => false,
+        'CONNECT_TIMEOUT'       => '',
+        'TIMEOUT'               => 30,
+        'USER_AGENT'            => '',
+        'URL'                   => '',
+        'POST'                  => false,
+        'HTTP_HEADER'           => array(),
+    );
+
+    protected $packageOptions = array(
+        'data'                  => array(),
+        'asJson'                => false,
+    );
+
+
+    /**
+     *  Set the URL to which the request is to be sent
+     * @param $url string   The URL to which the request is to be sent
+     * @return $this
+     */
+    public function to($url)
+    {
+        return $this->withCurlOption( 'URL', $url );
+    }
+
+    /**
+     *  Set the request timeout
+     * @param $timeout integer  The timeout for the request (in seconds. Default: 30 seconds)
+     * @return $this
+     */
+    public function withTimeout($timeout = 30)
+    {
+        return $this->withCurlOption( 'TIMEOUT', $timeout );
+    }
+
+    /**
+     *  Add GET or POST data to the request
+     * @param $data array   Array of data that is to be sent along wiht the request
+     * @return $this
+     */
+    public function withData($data = array())
+    {
+        return $this->withPackageOption( 'data', $data );
+    }
+
+    /**
+     *  Configure the package to encode and decode the request data
+     * @return $this
+     */
+    public function asJson()
+    {
+        return $this->withPackageOption( 'asJson', true );
+    }
+
+//    /**
+//     *  Send the request over a secure connection
+//     * @return $this
+//     */
+//    public function secure()
+//    {
+//        return $this;
+//    }
+
+    /**
+     *  Set any specific cURL option
+     * @param $key string       The name of the cURL option
+     * @param $value string     The value to which the option is to be set
+     * @return $this
+     */
+    public function withOption($key, $value)
+    {
+        return $this->withCurlOption( $key, $value );
+    }
+
+    /**
+     *  Set any specific cURL option
+     * @param $key string       The name of the cURL option
+     * @param $value string     The value to which the option is to be set
+     * @return $this
+     */
+    protected function withCurlOption($key, $value)
+    {
+        $this->curlOptions[ $key ] = $value;
+
+        return $this;
+    }
+
+    /**
+     *  Set any specific package option
+     * @param $key string       The name of the cURL option
+     * @param $value string     The value to which the option is to be set
+     * @return $this
+     */
+    protected function withPackageOption($key, $value)
+    {
+        $this->packageOptions[ $key ] = $value;
+
+        return $this;
+    }
+
+    /**
+     *  Add a HTTP header to the request
+     * @param $header string    The HTTP header that is to be added to the request
+     * @return $this
+     */
+    public function withHeader($header)
+    {
+        $this->curlOptions[ 'HTTP_HEADER' ][] = $header;
+    }
+
+    /**
+     *  Send a GET request to a URL using the specified cURL options
+     * @return mixed
+     */
+    public function get()
+    {
+        $parameterString = '';
+        if( is_array($this->packageOptions[ 'data' ]) && count($this->packageOptions[ 'data' ]) != 0 ) {
+            $parameterString = '?'. http_build_query($this->packageOptions[ 'data' ]);
+        }
+
+        $this->curlOptions[ 'URL' ] .= $parameterString;
+
+        return $this->send();
+    }
+
+    /**
+     *  Send a POST request to a URL using the specified cURL options
+     * @return mixed
+     */
+    public function post()
+    {
+        $this->setPostParameters();
+
+        return $this->send();
+    }
+
+    /**
+     * Add POST parameters to the curlOptions array
+     */
+    protected function setPostParameters()
+    {
+        $this->curlOptions[ 'POST' ] = true;
+
+        $parameters = $this->packageOptions[ 'data' ];
+        if( $this->packageOptions[ 'asJson' ] ) {
+            $parameters = json_encode($parameters);
+        }
+
+        $this->curlOptions[ 'POST_FIELDS' ] = $parameters;
+    }
+
+//    /**
+//     *  Send a PUT request to a URL using the specified cURL options
+//     * @return mixed
+//     */
+//    public function put()
+//    {
+//        $this->setPostParameters();
+//
+//        return $this->send();
+//    }
+//
+//    /**
+//     *  Send a DELETE request to a URL using the specified cURL options
+//     * @return mixed
+//     */
+//    public function delete()
+//    {
+//        $this->setPostParameters();
+//
+//        return $this->send();
+//    }
+
+    /**
+     *  Send the request
+     * @return mixed
+     */
+    protected function send()
+    {
+        // Add JSON header if necessary
+        if( $this->packageOptions[ 'asJson' ] ) {
+            $this->withHeader( 'Content-Type: application/json' );
+        }
+
+        // Create the request with all specified options
+        $this->curlObject = curl_init();
+        $options = $this->forgeOptions();
+        curl_setopt_array( $this->curlObject, $options );
+
+        // Send the request
+        $response = curl_exec( $this->curlObject );
+        curl_close( $this->curlObject );
+
+        // Decode the request if necessary
+        if( $this->packageOptions[ 'asJson' ] ) {
+            $response = json_decode($response);
+        }
+
+        // Return the result
+        return $response;
+    }
+
+    /**
+     *  Convert the curlOptions to an array of usable options for the cURL request
+     * @return array
+     */
+    protected function forgeOptions()
+    {
+        $results = array();
+        foreach( $this->curlOptions as $key => $value ) {
+            $array_key = constant( 'CURLOPT_' . str_replace('_', '', $key) );
+
+            if( $key == 'POST_FIELDS' && is_array( $value ) ) {
+                $results[ $array_key ] = http_build_query( $value, null, '&' );
+            } else {
+                $results[ $array_key ] = $value;
+            }
+        }
+
+        return $results;
+    }
+
+}

+ 0 - 75
src/Ixudra/Curl/Curl.php

@@ -1,75 +0,0 @@
-<?php namespace Ixudra\Curl;
-
-
-class Curl {
-
-    protected $curlObject = null;
-
-    protected $options = array(
-        'RETURN_TRANSFER'       => true,
-        'FAIL_ON_ERROR'         => true,
-        'FOLLOW_LOCATION'       => false,
-        'CONNECT_TIMEOUT'       => '',
-        'TIMEOUT'               => 30,
-        'USER_AGENT'            => '',
-        'URL'                   => '',
-        'POST'                  => false,
-        'HTTP_HEADER'           => array()
-    );
-
-
-    public function send()
-    {
-        $this->curlObject = curl_init();
-        $options = $this->forgeOptions();
-        curl_setopt_array( $this->curlObject, $options );
-
-        $response = curl_exec( $this->curlObject );
-        curl_close( $this->curlObject );
-
-        return $response;
-    }
-
-    public function setUrl($baseUrl, $getParameters = array())
-    {
-        $parameterString = '';
-        if( is_array($getParameters) && count($getParameters) != 0 ) {
-            $parameterString = '?'. http_build_query($getParameters);
-        }
-
-        return $this->options[ 'URL' ] = $baseUrl . $parameterString;
-    }
-
-    public function setMethod($method)
-    {
-        $this->options[ 'POST' ] = $method;
-    }
-
-    public function setPostParameters($parameters)
-    {
-        $this->options[ 'POST' ] = true;
-        $this->options[ 'POST_FIELDS' ] = $parameters;
-    }
-
-    public function addOption($key, $value)
-    {
-        $this->options[ $key ] = $value;
-    }
-
-    protected function forgeOptions()
-    {
-        $results = array();
-        foreach( $this->options as $key => $value ) {
-            $array_key = constant( 'CURLOPT_' . str_replace('_', '', $key) );
-
-            if( $key == 'POST_FIELDS' && is_array( $value ) ) {
-                $results[ $array_key ] = http_build_query( $value, null, '&' );
-            } else {
-                $results[ $array_key ] = $value;
-            }
-        }
-
-        return $results;
-    }
-
-}

+ 7 - 38
src/Ixudra/Curl/CurlService.php

@@ -3,46 +3,15 @@
 
 class CurlService {
 
-    public function get($url, $getParameters = array(), $isJson = false, $curlOptions = array())
+    /**
+     * @param $url string   The URL to which the request is to be sent
+     * @return \Ixudra\Curl\Builder
+     */
+    public function to($url)
     {
-        $curl = new Curl();
-        $curl->setUrl( $url, $getParameters );
+        $builder = new Builder();
 
-        foreach( $curlOptions as $key => $value ) {
-            $curl->addOption( $key, $value );
-        }
-
-        return $this->send( $curl, $isJson );
-    }
-
-    public function post($url, $getParameters = array(), $postParameters, $isJson = false, $curlOptions = array())
-    {
-        $curl = new Curl();
-        $curl->setUrl( $url, $getParameters );
-        $curl->setMethod( true );
-
-        if( $isJson ) {
-            $postParameters = json_encode($postParameters);
-            $curl->addOption( 'HTTP_HEADER', array('Content-Type: application/json') );
-        }
-
-        $curl->setPostParameters( $postParameters );
-
-        foreach( $curlOptions as $key => $value ) {
-            $curl->addOption( $key, $value );
-        }
-
-        return $this->send( $curl, $isJson );
-    }
-
-    protected function send($curl, $isJson)
-    {
-        $response = $curl->send();
-        if( $isJson ) {
-            $response = json_decode($response);
-        }
-
-        return $response;
+        return $builder->to($url);
     }
 
 }