public function seeCurrentRouteIs($route, $params = array())
    {
        $this->seeCurrentUrlEquals($this->app['url']->route($route, $params, false));
    }

public function seeCurrentRouteIs ( $ route , $ params = array ( ) ) { $ this -> seeCurrentUrlEquals ( $ this -> app [ 'url' ] -> route ( $ route , $ params , false ) ) ; }

Checks that current url matches route

```php
<?php
$I->seeCurrentRouteIs('posts.index');
?>
```
@param $route
@param array $params


public function seeCurrentActionIs($action, $params = array())
    {
        $this->seeCurrentUrlEquals($this->app['url']->action($action, $params, false));
    }

public function seeCurrentActionIs ( $ action , $ params = array ( ) ) { $ this -> seeCurrentUrlEquals ( $ this -> app [ 'url' ] -> action ( $ action , $ params , false ) ) ; }

Checks that current url matches action

```php
<?php
$I->seeCurrentActionIs('PostsController@index');
?>
```

@param $action
@param array $params


public function seeInSession($key, $value = null)
    {
        if (is_array($key)) {
            $this->seeSessionHasValues($key);
            return;
        }

        if (is_null($value)) {
            $this->assertTrue($this->app['session']->has($key));
        } else {
            $this->assertEquals($value, $this->app['session']->get($key));
        }
    }

public function seeInSession ( $ key , $ value = null ) { if ( is_array ( $ key ) ) { $ this -> seeSessionHasValues ( $ key ) ; return ; } if ( is_null ( $ value ) ) { $ this -> assertTrue ( $ this -> app [ 'session' ] -> has ( $ key ) ) ; } else { $ this -> assertEquals ( $ value , $ this -> app [ 'session' ] -> get ( $ key ) ) ; } }

Assert that the session has a given list of values.

@param  string|array $key
@param  mixed $value
@return void

Assert that the session has a given list of values .


public function seeFormHasErrors()
    {
        $viewErrorBag = $this->app->make('view')->shared('errors');
        $this->assertTrue(count($viewErrorBag) > 0);
    }

public function seeFormHasErrors ( ) { $ viewErrorBag = $ this -> app -> make ( 'view' ) -> shared ( 'errors' ) ; $ this -> assertTrue ( count ( $ viewErrorBag ) > 0 ) ; }

Assert that the form errors are bound to the View.

@return bool

Assert that the form errors are bound to the View .


public function seeFormErrorMessage($key, $errorMessage)
    {
        $viewErrorBag = $this->app['view']->shared('errors');

        $this->assertEquals($errorMessage, $viewErrorBag->first($key));
    }

public function seeFormErrorMessage ( $ key , $ errorMessage ) { $ viewErrorBag = $ this -> app [ 'view' ] -> shared ( 'errors' ) ; $ this -> assertEquals ( $ errorMessage , $ viewErrorBag -> first ( $ key ) ) ; }

Assert that specific form error message is set in the view.

Useful for validation messages and generally messages array
e.g.
return `Redirect::to('register')->withErrors($validator);`

Example of Usage

``` php
<?php
$I->seeFormErrorMessage('username', 'Invalid Username');
?>
```
@param string $key
@param string $errorMessage

Assert that specific form error message is set in the view .


public function amLoggedAs($user, $driver = null)
    {
        if ($user instanceof Authenticatable) {
            $this->app['auth']->driver($driver)->setUser($user);
        } else {
            $this->app['auth']->driver($driver)->attempt($user);
        }
    }

public function amLoggedAs ( $ user , $ driver = null ) { if ( $ user instanceof Authenticatable ) { $ this -> app [ 'auth' ] -> driver ( $ driver ) -> setUser ( $ user ) ; } else { $ this -> app [ 'auth' ] -> driver ( $ driver ) -> attempt ( $ user ) ; } }

Set the currently logged in user for the application.
Takes either an object that implements the User interface or
an array of credentials.

@param  \Illuminate\Contracts\Auth\User|array $user
@param  string $driver
@return void

Set the currently logged in user for the application . Takes either an object that implements the User interface or an array of credentials .


public function haveRecord($model, $attributes = array())
    {
        $id = $this->app['db']->table($model)->insertGetId($attributes);
        if (!$id) {
            $this->fail("Couldn't insert record into table $model");
        }
        return $id;
    }

Inserts record into the database.

``` php
<?php
$user_id = $I->haveRecord('users', array('name' => 'Davert'));
?>
```

@param $model
@param array $attributes
@return mixed


public function transform($value)
    {
        if (null === $value) {
            return '';
        }

        if (!is_numeric($value)) {
            throw new TransformationFailedException('Expected a numeric.');
        }

        $formatter = $this->getNumberFormatter();
        $value = $formatter->format($value);

        if (intl_is_failure($formatter->getErrorCode())) {
            throw new TransformationFailedException($formatter->getErrorMessage());
        }

        // Convert fixed spaces to normal ones
        $value = str_replace("\xc2\xa0", ' ', $value);

        return $value;
    }

public
function
transform
(
$
value
)
{
if
(
===
$
value
)
{
return
''
;
}
if
(
!
is_numeric
(
$
value
)
)
{
throw
new
TransformationFailedException
(
'Expected a numeric.'
)
;
}
$
formatter
=
$
this
->
getNumberFormatter
(
)
;
$
value
=
$
formatter
->
format
(
$
value
)
;
if
(
intl_is_failure
(
$
formatter
->
getErrorCode
(
)
)
)
{
throw
new
TransformationFailedException
(
$
formatter
->
getErrorMessage
(
)
)
;
}
// Convert fixed spaces to normal ones
$
value
=
str_replace
(
"\xc2\xa0"
,
' '
,
$
value
)
;
return
$
value
;
}

Transforms a number type into localized number.

@param int|float $value Number value

@throws TransformationFailedException If the given value is not numeric
or if the value can not be transformed

@return string Localized value

Transforms a number type into localized number .


protected function getNumberFormatter($type = \NumberFormatter::DECIMAL)
    {
        $formatter = new \NumberFormatter(\Locale::getDefault(), $type);

        if (null !== $this->precision) {
            $formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $this->precision);
            $formatter->setAttribute(\NumberFormatter::ROUNDING_MODE, $this->roundingMode);
        }

        $formatter->setAttribute(\NumberFormatter::GROUPING_USED, $this->grouping);

        return $formatter;
    }

protected function getNumberFormatter ( $ type = \ NumberFormatter :: DECIMAL ) { $ formatter = new \ NumberFormatter ( \ Locale :: getDefault ( ) , $ type ) ; if ( null !== $ this -> precision ) { $ formatter -> setAttribute ( \ NumberFormatter :: FRACTION_DIGITS , $ this -> precision ) ; $ formatter -> setAttribute ( \ NumberFormatter :: ROUNDING_MODE , $ this -> roundingMode ) ; } $ formatter -> setAttribute ( \ NumberFormatter :: GROUPING_USED , $ this -> grouping ) ; return $ formatter ; }

Returns a preconfigured \NumberFormatter instance.

@param int $type

@return \NumberFormatter

Returns a preconfigured \ NumberFormatter instance .


public static function nest(array $data, $seperator = '_')
    {
        if (self::isAssoc($data)) {
            $result = new \stdClass();

            foreach ($data as $key => $value) {
                if (($pos = strpos($key, $seperator)) !== false) {
                    $subKey = substr($key, 0, $pos);
                    $name   = substr($key, $pos + 1);

                    if (!isset($result->{$subKey})) {
                        $result->{$subKey} = self::nest(self::getParts($data, $subKey . $seperator), $seperator);
                    }
                } else {
                    $result->{$key} = $value;
                }
            }

            return $result;
        } else {
            $result = [];

            foreach ($data as $value) {
                $result[] = self::nest($value, $seperator);
            }

            return $result;
        }
    }

public static function nest ( array $ data , $ seperator = '_' ) { if ( self :: isAssoc ( $ data ) ) { $ result = new \ stdClass ( ) ; foreach ( $ data as $ key => $ value ) { if ( ( $ pos = strpos ( $ key , $ seperator ) ) !== false ) { $ subKey = substr ( $ key , 0 , $ pos ) ; $ name = substr ( $ key , $ pos + 1 ) ; if ( ! isset ( $ result -> { $ subKey } ) ) { $ result -> { $ subKey } = self :: nest ( self :: getParts ( $ data , $ subKey . $ seperator ) , $ seperator ) ; } } else { $ result -> { $ key } = $ value ; } } return $ result ; } else { $ result = [ ] ; foreach ( $ data as $ value ) { $ result [ ] = self :: nest ( $ value , $ seperator ) ; } return $ result ; } }

Converts a flat array into a nested object using a seperator

@param array $data
@param string $seperator
@return \stdClass


public static function flatten($data, $seperator = '_', $prefix = null, array &$result = null)
    {
        if ($result === null) {
            $result = array();
        }

        if ($data instanceof \stdClass) {
            $data = (array) $data;
        } elseif (!is_array($data)) {
            throw new InvalidArgumentException('Data must be either an stdClass or array');
        }

        foreach ($data as $key => $value) {
            if ($value instanceof \stdClass || is_array($value)) {
                self::flatten($value, $seperator, $prefix . $key . $seperator, $result);
            } else {
                $result[$prefix . $key] = $value;
            }
        }

        return $result;
    }

Converts a nested array into a flat using a seperator. The prefix and
result parameter are used internally for performance reason and should
not be used

@param array $data
@param string $seperator
@param string $prefix
@param array $result
@return array

Converts a nested array into a flat using a seperator . The prefix and result parameter are used internally for performance reason and should not be used


public static function objectify(array $data)
    {
        if (self::isAssoc($data)) {
            $result = new \stdClass();
            foreach ($data as $key => $value) {
                $result->{$key} = is_array($value) ? self::objectify($value) : $value;
            }

            return $result;
        } else {
            $result = [];
            foreach ($data as $value) {
                $result[] = is_array($value) ? self::objectify($value) : $value;
            }

            return $result;
        }
    }

public static function objectify ( array $ data ) { if ( self :: isAssoc ( $ data ) ) { $ result = new \ stdClass ( ) ; foreach ( $ data as $ key => $ value ) { $ result -> { $ key } = is_array ( $ value ) ? self :: objectify ( $ value ) : $ value ; } return $ result ; } else { $ result = [ ] ; foreach ( $ data as $ value ) { $ result [ ] = is_array ( $ value ) ? self :: objectify ( $ value ) : $ value ; } return $ result ; } }

Replaces all associative arrays with stdClass in an arbitrary array
structure

@param array $data
@return \stdClass|array


public function createColumn(string $name, array $options = []): ColumnInterface
    {
        $options = $this->getOptionsResolver()->resolve($options);

        return $this->newColumn($name, $options);
    }

public function createColumn ( string $ name , array $ options = [ ] ) : ColumnInterface { $ options = $ this -> getOptionsResolver ( ) -> resolve ( $ options ) ; return $ this -> newColumn ( $ name , $ options ) ; }

Returns a new ColumnInterface instance.

@param string $name
@param array  $options

@return ColumnInterface

Returns a new ColumnInterface instance .


public function buildHeaderView(HeaderView $view, ColumnInterface $column, array $options)
    {
        if (null !== $this->parent) {
            $this->parent->buildHeaderView($view, $column, $options);
        }

        $this->innerType->buildHeaderView($view, $column, $options);

        foreach ($this->typeExtensions as $extension) {
            $extension->buildHeaderView($view, $column, $options);
        }
    }

public function buildHeaderView ( HeaderView $ view , ColumnInterface $ column , array $ options ) { if ( null !== $ this -> parent ) { $ this -> parent -> buildHeaderView ( $ view , $ column , $ options ) ; } $ this -> innerType -> buildHeaderView ( $ view , $ column , $ options ) ; foreach ( $ this -> typeExtensions as $ extension ) { $ extension -> buildHeaderView ( $ view , $ column , $ options ) ; } }

Configures a header view for the type hierarchy.

@param HeaderView      $view
@param ColumnInterface $column
@param array           $options

Configures a header view for the type hierarchy .


public function buildCellView(CellView $view, ColumnInterface $column, array $options)
    {
        if (null !== $this->parent) {
            $this->parent->buildCellView($view, $column, $options);
        }

        $this->innerType->buildCellView($view, $column, $options);

        foreach ($this->typeExtensions as $extension) {
            $extension->buildCellView($view, $column, $options);
        }
    }

public function buildCellView ( CellView $ view , ColumnInterface $ column , array $ options ) { if ( null !== $ this -> parent ) { $ this -> parent -> buildCellView ( $ view , $ column , $ options ) ; } $ this -> innerType -> buildCellView ( $ view , $ column , $ options ) ; foreach ( $ this -> typeExtensions as $ extension ) { $ extension -> buildCellView ( $ view , $ column , $ options ) ; } }

Configures a cell view for the type hierarchy.

@param CellView        $view
@param ColumnInterface $column
@param array           $options

Configures a cell view for the type hierarchy .


protected function newColumn($name, array $options): ColumnInterface
    {
        // Special case of CompoundColumnType which requires that child columns
        // are set afterwards. Whenever you extend this class, make sure to honor this
        // special use-case.
        if (null === $this->compound) {
            $this->compound = $this->isCompound();
        }

        if ($this->compound) {
            return new CompoundColumn($name, $this, $options);
        }

        return new Column($name, $this, $options);
    }

Creates a new Column instance.

Override this method if you want to customize the Column class.

@param string $name    The name of the column
@param array  $options The builder options

@return ColumnInterface The new column instance


protected function isCompound(): bool
    {
        if ($this->innerType instanceof CompoundColumnType) {
            return true;
        }

        for ($type = $this->parent; null !== $type; $type = $type->getParent()) {
            if ($type->getInnerType() instanceof CompoundColumnType) {
                return true;
            }
        }

        return false;
    }

protected function isCompound ( ) : bool { if ( $ this -> innerType instanceof CompoundColumnType ) { return true ; } for ( $ type = $ this -> parent ; null !== $ type ; $ type = $ type -> getParent ( ) ) { if ( $ type -> getInnerType ( ) instanceof CompoundColumnType ) { return true ; } } return false ; }

Determines whether this type is a compound.

@return bool

Determines whether this type is a compound .


protected function getBaseData()
    {
        $data = array();
        $data['GatewayUserName'] = $this->getUsername();
        $data['GatewayPassword'] = $this->getPassword();
        $data['PaymentType'] = $this->paymentType;

        if (isset($this->transactionType)) {
            $data['TransactionType'] = $this->transactionType;
        }
        if (isset($this->safeAction)) {
            $data['SAFE_Action'] = $this->safeAction;
        }
        return $data;
    }

protected function getBaseData ( ) { $ data = array ( ) ; $ data [ 'GatewayUserName' ] = $ this -> getUsername ( ) ; $ data [ 'GatewayPassword' ] = $ this -> getPassword ( ) ; $ data [ 'PaymentType' ] = $ this -> paymentType ; if ( isset ( $ this -> transactionType ) ) { $ data [ 'TransactionType' ] = $ this -> transactionType ; } if ( isset ( $ this -> safeAction ) ) { $ data [ 'SAFE_Action' ] = $ this -> safeAction ; } return $ data ; }

Get the gateway base data

@return array


protected function getShippingData()
    {
        $data = array();
        // Customer shipping details
        if ($card = $this->getCard()) {
            // Customer shipping details
            if ($card->getShippingFirstName()) {
                $data['ShippingFirstName'] = $card->getShippingFirstName();
            }
            if ($card->getShippingLastName()) {
                $data['ShippingLastName'] = $card->getShippingLastName();
            }
            if ($card->getShippingCompany()) {
                $data['ShippingCompany'] = $card->getShippingCompany();
            }
            if ($card->getShippingAddress1()) {
                $data['ShippingAddress1'] = $card->getShippingAddress1();
            }
            if ($card->getShippingAddress2()) {
                $data['ShippingAddress2'] = $card->getShippingAddress2();
            }
            if ($card->getShippingCity()) {
                $data['ShippingCity'] = $card->getShippingCity();
            }
            if ($card->getShippingState()) {
                $data['ShippingState'] = $card->getShippingState();
            }
            if ($card->getShippingPostcode()) {
                $data['ShippingZip'] = $card->getShippingPostcode();
            }
            if ($card->getShippingCountry()) {
                $data['ShippingCountry'] = $card->getShippingCountry();
            }
        }
        return $data;
    }

protected
function
getShippingData
(
)
{
$
data
=
array
(
)
;
// Customer shipping details
if
(
$
card
=
$
this
->
getCard
(
)
)
{
// Customer shipping details
if
(
$
card
->
getShippingFirstName
(
)
)
{
$
data
[
'ShippingFirstName'
]
=
$
card
->
getShippingFirstName
(
)
;
}
if
(
$
card
->
getShippingLastName
(
)
)
{
$
data
[
'ShippingLastName'
]
=
$
card
->
getShippingLastName
(
)
;
}
if
(
$
card
->
getShippingCompany
(
)
)
{
$
data
[
'ShippingCompany'
]
=
$
card
->
getShippingCompany
(
)
;
}
if
(
$
card
->
getShippingAddress1
(
)
)
{
$
data
[
'ShippingAddress1'
]
=
$
card
->
getShippingAddress1
(
)
;
}
if
(
$
card
->
getShippingAddress2
(
)
)
{
$
data
[
'ShippingAddress2'
]
=
$
card
->
getShippingAddress2
(
)
;
}
if
(
$
card
->
getShippingCity
(
)
)
{
$
data
[
'ShippingCity'
]
=
$
card
->
getShippingCity
(
)
;
}
if
(
$
card
->
getShippingState
(
)
)
{
$
data
[
'ShippingState'
]
=
$
card
->
getShippingState
(
)
;
}
if
(
$
card
->
getShippingPostcode
(
)
)
{
$
data
[
'ShippingZip'
]
=
$
card
->
getShippingPostcode
(
)
;
}
if
(
$
card
->
getShippingCountry
(
)
)
{
$
data
[
'ShippingCountry'
]
=
$
card
->
getShippingCountry
(
)
;
}
}
return
$
data
;
}


protected function getInvoiceData()
    {
        $data = array();
        $data['Amount'] = $this->getAmount();
        if ($this->getDescription()) {
            $data['OrderDescription'] = $this->getDescription();
        }
        return $data;
    }

protected function getInvoiceData ( ) { $ data = array ( ) ; $ data [ 'Amount' ] = $ this -> getAmount ( ) ; if ( $ this -> getDescription ( ) ) { $ data [ 'OrderDescription' ] = $ this -> getDescription ( ) ; } return $ data ; }


public function sendData($data)
    {
        $xml = $this->buildRequest($data);

        $headers = array(
            'content-type' => 'text/xml; charset=utf-8',
            'SOAPAction' => 'https://gateway.agms.com/roxapi/ProcessTransaction'
        );

        $httpResponse =  $this->httpClient->post($this->getEndpoint(), $headers, $xml)->send();
        return $this->response = new Response($this, $httpResponse->getBody());
    }

Send the request

@return AbstractResponse


public static function trim(string $string): string
    {
        if (null !== $result = @preg_replace('/^[\pZ\p{Cc}]+|[\pZ\p{Cc}]+$/u', '', $string)) {
            return $result;
        }

        return trim($string);
    }

public static function trim ( string $ string ) : string { if ( null !== $ result = @ preg_replace ( '/^[\pZ\p{Cc}]+|[\pZ\p{Cc}]+$/u' , '' , $ string ) ) { return $ result ; } return trim ( $ string ) ; }

Returns the trimmed data.

@param string $string

@return string


public static function fqcnToBlockPrefix(string $fqcn): string
    {
        // Non-greedy ("+?") to match "type" suffix, if present
        if (preg_match('~([^\\\\]+?)(type)?$~i', $fqcn, $matches)) {
            return strtolower(
                preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], ['\\1_\\2', '\\1_\\2'], $matches[1])
            );
        }
    }

Converts a fully-qualified class name to a block prefix.

@param string $fqcn The fully-qualified class name

@return string|null The block prefix or null if not a valid FQCN

Converts a fully - qualified class name to a block prefix .


public function transform($value)
    {
        if (null === $value) {
            return '';
        }

        if (is_array($value)) {
            return $this->doTransformation($value['currency'] ?: $this->defaultCurrency, (string) $value['amount']);
        }

        // Convert fixed spaces to normal ones.
        $value = str_replace("\xc2\xa0", ' ', (string) $value);

        if (false !== strpos($value, ' ')) {
            return $this->transformStringWithCurrencyToLocalized($value);
        }

        return $this->doTransformation($this->defaultCurrency, $value);
    }

public
function
transform
(
$
value
)
{
if
(
===
$
value
)
{
return
''
;
}
if
(
is_array
(
$
value
)
)
{
return
$
this
->
doTransformation
(
$
value
[
'currency'
]
:
$
this
->
defaultCurrency
,
(
string
)
$
value
[
'amount'
]
)
;
}
// Convert fixed spaces to normal ones.
$
value
=
str_replace
(
"\xc2\xa0"
,
' '
,
(
string
)
$
value
)
;
if
(
false
!==
strpos
(
$
value
,
' '
)
)
{
return
$
this
->
transformStringWithCurrencyToLocalized
(
$
value
)
;
}
return
$
this
->
doTransformation
(
$
this
->
defaultCurrency
,
$
value
)
;
}

Transforms a normalized format into a localized money string.

@param string|int|float|array $value

@throws TransformationFailedException If the given value is not numeric or
if the value can not be transformed

@return string Localized money string

Transforms a normalized format into a localized money string .


protected function parseValue($value)
    {
        if (is_numeric($value)) {
            return strpos($value, '.') !== false ? (float) $value : (int) $value;
        } elseif ($value === 'true' || $value === '1') {
            return true;
        } elseif ($value === 'false' || $value === '0') {
            return false;
        } else {
            return $value;
        }
    }

protected function parseValue ( $ value ) { if ( is_numeric ( $ value ) ) { return strpos ( $ value , '.' ) !== false ? ( float ) $ value : ( int ) $ value ; } elseif ( $ value === 'true' || $ value === '1' ) { return true ; } elseif ( $ value === 'false' || $ value === '0' ) { return false ; } else { return $ value ; } }

In XML we have now information about the data type but in the jsonschema
we require a specific type. This method tries to guess the correct type

@param string $value
@return mixed

In XML we have now information about the data type but in the jsonschema we require a specific type . This method tries to guess the correct type


public function add(string $name, string $type = null, array $options = []): CompoundColumnBuilderInterface
    {
        $this->unresolvedColumns[$name] = [
            'type' => $type,
            'options' => $options,
        ];

        return $this;
    }

public function add ( string $ name , string $ type = null , array $ options = [ ] ) : CompoundColumnBuilderInterface { $ this -> unresolvedColumns [ $ name ] = [ 'type' => $ type , 'options' => $ options , ] ; return $ this ; }

Add a column to the builder.

@param string $name
@param string $type
@param array  $options

@return self


protected function isValidUpload()
    {
        $error = $this->error ?: UPLOAD_ERR_NO_FILE;

        switch ($error) {
            case UPLOAD_ERR_OK:
                return $this->isUploadedFile();
                break;

            case UPLOAD_ERR_INI_SIZE:
                throw new \RuntimeException('The uploaded file exceeds the upload_max_filesize directive in php.ini');
                break;

            case UPLOAD_ERR_FORM_SIZE:
                throw new \RuntimeException('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form');
                break;

            case UPLOAD_ERR_PARTIAL:
                throw new \RuntimeException('The uploaded file was only partially uploaded');
                break;

            case UPLOAD_ERR_NO_FILE:
                throw new \RuntimeException('No file was uploaded');
                break;

            case UPLOAD_ERR_NO_TMP_DIR:
                throw new \RuntimeException('Missing a temporary folder');
                break;

            case UPLOAD_ERR_CANT_WRITE:
                throw new \RuntimeException('Failed to write file to disk');
                break;

            case UPLOAD_ERR_EXTENSION:
                throw new \RuntimeException('A PHP extension stopped the file upload');
                break;

            default:
                throw new \RuntimeException('Invalid error code');
                break;
        }
    }

Checks whether the file upload is valid

@return boolean


public static function resolve(string $filename, string $basePath = ''): string
    {
        if (strpos($filename, '://')) {
            //Absolute path
            return $filename;
        }

        $localFilename = directory('public') . $filename;

        //Add query parameter to uniquely identify file version
        if (is_file($localFilename) && file_exists($localFilename)) {
            $filename .= '?' . hash('crc32', filemtime($localFilename));
        }

        return str_replace('//', '/', $basePath . $filename);
    }

Create filename query signature. Attention, this method work only for resources located in
public directory.

@param string $filename
@param string $basePath Application base path prefix.

@return string

Create filename query signature . Attention this method work only for resources located in public directory .


public function updateForm($form, $record)
    {
        if (!$record) {
            return;
        }
        // if the current user can't edit the record anyway, we don't need to do anything
        if ($record && !$record->canEdit()) {
            return $form;
        }

        // check if all classes should be locked by default or a certain list
        $lockedClasses = Config::inst()->get('EditLockControllerExtension', 'lockedClasses');
        if (!empty($lockedClasses)) {
            if (!in_array($record->ClassName, $lockedClasses)) {
                return $form;
            }
        }

        // check if this record is being edited by another user
        $beingEdited = RecordBeingEdited::get()->filter(array(
            'RecordID' => $record->ID,
            'RecordClass' => $record->ClassName,
            'EditorID:not' => Member::currentUserID()
        ))->first();

        if ($beingEdited) {
            if ($this->owner->getRequest()->getVar('editanyway') == '1') {
                $beingEdited->isEditingAnyway();
                return Controller::curr()->redirectBack();
            }
            // if the RecordBeingEdited record has not been updated in the last 15 seconds (via ping)
            // the person editing it must have left the edit form, so delete the RecordBeingEdited
            if (strtotime($beingEdited->LastEdited) < (time() - 15)) {
                $beingEdited->delete();
            // otherwise, there must be someone currently editing this record, so make the form readonly
            // unless they have permission to, and have chosen to edit anyway
            } else {
                if (!$beingEdited->isEditingAnyway()) {
                    $readonlyFields = $form->Fields()->makeReadonly();
                    $form->setFields($readonlyFields);
                    $form->addExtraClass('edit-locked');
                    $form->setAttribute('data-lockedmessage', $beingEdited->getLockedMessage());
                    return;
                }
            }
        }

        $form->setAttribute('data-recordclass', $record->ClassName);
        $form->setAttribute('data-recordid', $record->ID);
        $form->setAttribute('data-lockurl', $this->owner->link('lock'));
        return $form;
    }

Updtes the edit form based on whether it is being edited or not


public function updateEditForm($form)
    {
        if ($record = $form->getRecord()) {
            $form = $this->updateForm($form, $record);
        }
    }

public function updateEditForm ( $ form ) { if ( $ record = $ form -> getRecord ( ) ) { $ form = $ this -> updateForm ( $ form , $ record ) ; } }

Extension hook for LeftAndMain subclasses


public function updateItemEditForm($form)
    {
        if ($record = $form->getRecord()) {
            $form = $this->updateForm($form, $record);
        }
    }

public function updateItemEditForm ( $ form ) { if ( $ record = $ form -> getRecord ( ) ) { $ form = $ this -> updateForm ( $ form , $ record ) ; } }

Extension hook for GridFieldDetailForm_ItemRequest


public function lock($request)
    {
        $id = (int)$request->postVar('RecordID');
        $class = $request->postVar('RecordClass');

        $existing = RecordBeingEdited::get()->filter(array(
            'RecordID' => $id,
            'RecordClass' => $class,
            'EditorID' => Member::currentUserID()
        ))->first();

        if ($existing) {
            $existing->write(false, false, true);
        } else {
            $lock = RecordBeingEdited::create(array(
                'RecordID' => $id,
                'RecordClass' => $class,
                'EditorID' => Member::currentUserID()
            ));
            $lock->write();
        }
    }

public function lock ( $ request ) { $ id = ( int ) $ request -> postVar ( 'RecordID' ) ; $ class = $ request -> postVar ( 'RecordClass' ) ; $ existing = RecordBeingEdited :: get ( ) -> filter ( array ( 'RecordID' => $ id , 'RecordClass' => $ class , 'EditorID' => Member :: currentUserID ( ) ) ) -> first ( ) ; if ( $ existing ) { $ existing -> write ( false , false , true ) ; } else { $ lock = RecordBeingEdited :: create ( array ( 'RecordID' => $ id , 'RecordClass' => $ class , 'EditorID' => Member :: currentUserID ( ) ) ) ; $ lock -> write ( ) ; } }

Handles ajax pings to create a RecordBeingEdited lock or update an existing one


public function apply_config($config)
    {
        if (!is_array(reset($config)))
            $config = array($config);
        foreach ($config as $entry)
        {
            $pub = new PubControlClient($entry['uri']);
            if (array_key_exists('iss', $entry))
                $pub->set_auth_jwt(array('iss' => $entry['iss']),
                        $entry['key']);
            $this->clients[] = $pub;
        }
    }

public function apply_config ( $ config ) { if ( ! is_array ( reset ( $ config ) ) ) $ config = array ( $ config ) ; foreach ( $ config as $ entry ) { $ pub = new PubControlClient ( $ entry [ 'uri' ] ) ; if ( array_key_exists ( 'iss' , $ entry ) ) $ pub -> set_auth_jwt ( array ( 'iss' => $ entry [ 'iss' ] ) , $ entry [ 'key' ] ) ; $ this -> clients [ ] = $ pub ; } }

a URI or a URI and JWT authentication information.

a URI or a URI and JWT authentication information .


public function publish($channel, $item)
    {
        foreach ($this->clients as $client)
            $client->publish($channel, $item);
    }

public function publish ( $ channel , $ item ) { foreach ( $ this -> clients as $ client ) $ client -> publish ( $ channel , $ item ) ; }

specified channel for all of the configured PubControlClient instances.

specified channel for all of the configured PubControlClient instances .


public function load($locale): array
    {
        // if file not exists
        if (!\file_exists($this->getFilePath($locale))) {
            // if local support build in get translate from package.
            if ($this->isSupportLocal($locale)) {
                return include $this->getFilePath($locale, true);
            }

            return [];
        }

        return include $this->getFilePath($locale);
    }

load lang.

@param $locale

@return array


public function send(RequestInterface $request)
    {
        $this->request = $request;

        if ($this->httpClient instanceof ClientInterface || method_exists($this->httpClient, 'send')) {
            $this->response = $this->httpClient->send($request);
        } else {
            throw new \RuntimeException('HTTP Client must implement method send, and return ResponseInterface');
        }

        return $this->response;
    }

Send verification request

@param RequestInterface $request
@return ResponseInterface


private function buildFromParts(array $parts)
    {
        $this->withScheme(isset($parts['scheme']) ? $parts['scheme'] : '')
            ->withUserInfo(
                isset($parts['user']) ? $parts['user'] : '',
                isset($parts['pass']) ? ':'.$parts['pass'] : null
            )
            ->withHost(isset($parts['host']) ? $parts['host'] : '')
            ->withPort(!empty($parts['port']) ? $parts['port'] : null)
            ->withPath(isset($parts['path']) ? $parts['path'] : '')
            ->withQuery(isset($parts['query']) ? $parts['query'] : '')
            ->withFragment(isset($parts['fragment']) ? $parts['fragment'] : '');
    }

private function buildFromParts ( array $ parts ) { $ this -> withScheme ( isset ( $ parts [ 'scheme' ] ) ? $ parts [ 'scheme' ] : '' ) -> withUserInfo ( isset ( $ parts [ 'user' ] ) ? $ parts [ 'user' ] : '' , isset ( $ parts [ 'pass' ] ) ? ':' . $ parts [ 'pass' ] : null ) -> withHost ( isset ( $ parts [ 'host' ] ) ? $ parts [ 'host' ] : '' ) -> withPort ( ! empty ( $ parts [ 'port' ] ) ? $ parts [ 'port' ] : null ) -> withPath ( isset ( $ parts [ 'path' ] ) ? $ parts [ 'path' ] : '' ) -> withQuery ( isset ( $ parts [ 'query' ] ) ? $ parts [ 'query' ] : '' ) -> withFragment ( isset ( $ parts [ 'fragment' ] ) ? $ parts [ 'fragment' ] : '' ) ; }

Apply parse_url parts to a URI.

@param $parts array of parse_url parts.


public function store(CreateUserRequest $request)
    {
        $input = $request->all();

        $user = $this->userRepository->create($input);

        Flash::success(trans('l5starter::messages.create.success'));

        return redirect(route('admin.users.index'));
    }

public function store ( CreateUserRequest $ request ) { $ input = $ request -> all ( ) ; $ user = $ this -> userRepository -> create ( $ input ) ; Flash :: success ( trans ( 'l5starter::messages.create.success' ) ) ; return redirect ( route ( 'admin.users.index' ) ) ; }

Store a newly created User in storage.

@param CreateUserRequest $request

@return Response


public function edit($id)
    {
        $user = $this->userRepository->findWithoutFail($id);

        if (empty($user)) {
            Flash::error(trans('l5starter::messages.404_not_found'));

            return redirect(route('admin.users.index'));
        }

        return view('l5starter::admin.users.edit')->with('user', $user);
    }

public function edit ( $ id ) { $ user = $ this -> userRepository -> findWithoutFail ( $ id ) ; if ( empty ( $ user ) ) { Flash :: error ( trans ( 'l5starter::messages.404_not_found' ) ) ; return redirect ( route ( 'admin.users.index' ) ) ; } return view ( 'l5starter::admin.users.edit' ) -> with ( 'user' , $ user ) ; }

Show the form for editing the specified User.

@param  int $id

@return Response

Show the form for editing the specified User .


public function update($id, UpdateUserRequest $request)
    {
        $user = $this->userRepository->findWithoutFail($id);

        if (empty($user)) {
            Flash::error(trans('l5starter::messages.404_not_found'));

            return redirect(route('admin.users.index'));
        }

        $user = $this->userRepository->update($request->all(), $id);

        Flash::success(trans('l5starter::messages.update.success'));

        return redirect(route('admin.users.index'));
    }

public function update ( $ id , UpdateUserRequest $ request ) { $ user = $ this -> userRepository -> findWithoutFail ( $ id ) ; if ( empty ( $ user ) ) { Flash :: error ( trans ( 'l5starter::messages.404_not_found' ) ) ; return redirect ( route ( 'admin.users.index' ) ) ; } $ user = $ this -> userRepository -> update ( $ request -> all ( ) , $ id ) ; Flash :: success ( trans ( 'l5starter::messages.update.success' ) ) ; return redirect ( route ( 'admin.users.index' ) ) ; }

Update the specified User in storage.

@param  int              $id
@param UpdateUserRequest $request

@return Response


public function destroy($id)
    {
        $user = $this->userRepository->findWithoutFail($id);

        if (empty($user)) {
            Flash::error(trans('l5starter::messages.404_not_found'));

            return redirect(route('admin.users.index'));
        }

        $this->userRepository->delete($id);

        Flash::success(trans('l5starter::messages.delete.success'));

        return redirect(route('admin.users.index'));
    }

public function destroy ( $ id ) { $ user = $ this -> userRepository -> findWithoutFail ( $ id ) ; if ( empty ( $ user ) ) { Flash :: error ( trans ( 'l5starter::messages.404_not_found' ) ) ; return redirect ( route ( 'admin.users.index' ) ) ; } $ this -> userRepository -> delete ( $ id ) ; Flash :: success ( trans ( 'l5starter::messages.delete.success' ) ) ; return redirect ( route ( 'admin.users.index' ) ) ; }

Remove the specified User from storage.

@param  int $id

@return Response

Remove the specified User from storage .


public function createMpdfInstance(
        $format = 'A4',
        $fontSize = 0,
        $fontFamily = '',
        $marginLeft = 15,
        $marginRight = 15,
        $marginTop = 16,
        $marginBottom = 16,
        $marginHeader = 9,
        $marginFooter = 9,
        $orientation = 'P'
    )
    {
        if (!(is_array($format) && count($format) == 2) || !in_array(strtoupper($format), $this->getAcceptedFormats())) {
            $format = 'A4';
        }

        $constructorArgs = array(
            'utf-8',
            $this->validateFormat($format),
            (int)$fontSize,
            $fontFamily,
            (int)$marginLeft,
            (int)$marginRight,
            (int)$marginTop,
            (int)$marginBottom,
            (int)$marginHeader,
            (int)$marginFooter,
            $this->validateOrientation($orientation));

        $reflection = new \ReflectionClass('\mPDF');
        $this->mpdf = $reflection->newInstanceArgs($constructorArgs);
    }

public function createMpdfInstance ( $ format = 'A4' , $ fontSize = 0 , $ fontFamily = '' , $ marginLeft = 15 , $ marginRight = 15 , $ marginTop = 16 , $ marginBottom = 16 , $ marginHeader = 9 , $ marginFooter = 9 , $ orientation = 'P' ) { if ( ! ( is_array ( $ format ) && count ( $ format ) == 2 ) || ! in_array ( strtoupper ( $ format ) , $ this -> getAcceptedFormats ( ) ) ) { $ format = 'A4' ; } $ constructorArgs = array ( 'utf-8' , $ this -> validateFormat ( $ format ) , ( int ) $ fontSize , $ fontFamily , ( int ) $ marginLeft , ( int ) $ marginRight , ( int ) $ marginTop , ( int ) $ marginBottom , ( int ) $ marginHeader , ( int ) $ marginFooter , $ this -> validateOrientation ( $ orientation ) ) ; $ reflection = new \ ReflectionClass ( '\mPDF' ) ; $ this -> mpdf = $ reflection -> newInstanceArgs ( $ constructorArgs ) ; }

Create new mPDF instance.

$mpdf = new mPDF(
'',  mode - default ''
'',  format - A4, for example, default ''
0,   font size - default 0
'',  default font family
15,  margin_left
15,  margin right
16,  margin top
16,  margin bottom
9,   margin header
9,   margin footer
'L'  L - landscape, P - portrait
);

@param string $format
@param int    $fontSize
@param string $fontFamily
@param int    $marginLeft
@param int    $marginRight
@param int    $marginTop
@param int    $marginBottom
@param int    $marginHeader
@param int    $marginFooter
@param string $orientation


protected function addHostHeader(UriInterface $uri)
    {
        $host = $uri->getHost();
        if ($port = $uri->getPort()) {
            $host = sprintf('%s:%s', $host, $port);
        }

        $this->headers['host'] = array($host);
    }

protected function addHostHeader ( UriInterface $ uri ) { $ host = $ uri -> getHost ( ) ; if ( $ port = $ uri -> getPort ( ) ) { $ host = sprintf ( '%s:%s' , $ host , $ port ) ; } $ this -> headers [ 'host' ] = array ( $ host ) ; }


public function buildGuzzleRequest(RequestInterface $request)
    {
        $this->addCallable(function () use ($request) {
            return $this->buildForVersionThree($request);
        });

        $this->addCallable(function () use ($request) {
            return $this->buildForVersionFourOrFive($request);
        });

        $this->addCallable(function () use ($request) {
            return $this->buildForVersionSix($request);
        });

        $guzzleRequest = $this->executeCallableChain();

        if (null === $guzzleRequest) {
            throw new RequestException('Unknown Guzzle client, request instance can not be created.');
        }

        return $guzzleRequest;
    }

Build guzzle request based on Guzzle client version.

@param RequestInterface $request
@return mixed
@throws RequestException

Build guzzle request based on Guzzle client version .


protected function executeCallableChain()
    {
        $callableResult = null;
        foreach ($this->callableChain as $callable) {
            $callableResult = call_user_func($callable);

            if (null !== $callableResult) {
                break;
            }
        }

        return $callableResult;
    }

protected function executeCallableChain ( ) { $ callableResult = null ; foreach ( $ this -> callableChain as $ callable ) { $ callableResult = call_user_func ( $ callable ) ; if ( null !== $ callableResult ) { break ; } } return $ callableResult ; }

Execute callable chain and return callable result.

@return mixed

Execute callable chain and return callable result .


protected function checkClassExists($className, $throwException = true)
    {
        if (class_exists($className)) {
            return true;
        }

        if ($throwException) {
            throw new \BadMethodCallException(
                sprintf('%s not found. Please check your dependencies in composer.json', $className)
            );
        }

        return false;
    }

Check if class available

@param string $className
@param bool $throwException
@throw BadMethodCallException
@return bool


public function run()
    {
        $quit = false;
        while (!$quit)
        {
            \Mutex::lock($this->thread_mutex);
            if (count($this->req_queue) == 0)
            {
                \Cond::wait($this->thread_cond, $this->thread_mutex);
                if (count($this->req_queue) == 0)
                {
                    \Mutex::unlock($this->thread_mutex);
                    continue;
                }
            }
            $reqs = array();
            while (count($this->req_queue) > 0 and count($reqs) < 10)
            {
                $m = $this->req_queue->shift();
                if ($m[0] == 'stop')
                {
                    $quit = true;
                    break;
                }
                $reqs[] = array($m[1], $m[2], $m[3], $m[4]);
            }
            \Mutex::unlock($this->thread_mutex);
            if (count($reqs) > 0)
                $this->pubbatch($reqs);
        }
    }

public function run ( ) { $ quit = false ; while ( ! $ quit ) { \ Mutex :: lock ( $ this -> thread_mutex ) ; if ( count ( $ this -> req_queue ) == 0 ) { \ Cond :: wait ( $ this -> thread_cond , $ this -> thread_mutex ) ; if ( count ( $ this -> req_queue ) == 0 ) { \ Mutex :: unlock ( $ this -> thread_mutex ) ; continue ; } } $ reqs = array ( ) ; while ( count ( $ this -> req_queue ) > 0 and count ( $ reqs ) < 10 ) { $ m = $ this -> req_queue -> shift ( ) ; if ( $ m [ 0 ] == 'stop' ) { $ quit = true ; break ; } $ reqs [ ] = array ( $ m [ 1 ] , $ m [ 2 ] , $ m [ 3 ] , $ m [ 4 ] ) ; } \ Mutex :: unlock ( $ this -> thread_mutex ) ; if ( count ( $ reqs ) > 0 ) $ this -> pubbatch ( $ reqs ) ; } }


public function ensure_thread()
    {
        if (!$this->is_thread_running)
        {
            $this->is_thread_running = true;
            $this->thread_cond = \Cond::create();
            $this->thread_mutex = \Mutex::create();
            $this->start();
        }
    }

public function ensure_thread ( ) { if ( ! $ this -> is_thread_running ) { $ this -> is_thread_running = true ; $ this -> thread_cond = \ Cond :: create ( ) ; $ this -> thread_mutex = \ Mutex :: create ( ) ; $ this -> start ( ) ; } }

the consumer makes an asynchronous publish call.

the consumer makes an asynchronous publish call .


public function queue_req($req)
    {
        \Mutex::lock($this->thread_mutex);
        $this->req_queue[] = $req;
        \Cond::signal($this->thread_cond);
        \Mutex::unlock($this->thread_mutex);
    }

public function queue_req ( $ req ) { \ Mutex :: lock ( $ this -> thread_mutex ) ; $ this -> req_queue [ ] = $ req ; \ Cond :: signal ( $ this -> thread_cond ) ; \ Mutex :: unlock ( $ this -> thread_mutex ) ; }


public function pubbatch($reqs)
    {
        if (count($reqs) == 0)
            throw new \RuntimeException('reqs length == 0');
        $uri = $reqs[0][0];
        $auth_header = $reqs[0][1];
        $items = array();
        $callbacks = array();
        foreach ($reqs as $req)
        {
            $items[] = $req[2];
            $callbacks[] = $req[3];
        }
        $result = null;
        try
        {
            $this->pcc_utilities->pubcall($uri, $auth_header, $items);
            $result = array(true, '');
        }
        catch (\RuntimeException $exception)
        {
            $result = array(false, $exception->getMessage());
        }
        foreach ($callbacks as $callback)
            if (!is_null($callback))
            {
                call_user_func($callback, $result[0], $result[1]);
            }
    }

public
function
pubbatch
(
$
reqs
)
{
if
(
count
(
$
reqs
)
==
0
)
throw
new
\
RuntimeException
(
'reqs length == 0'
)
;
$
uri
=
$
reqs
[
0
]
[
0
]
;
$
auth_header
=
$
reqs
[
0
]
[
1
]
;
$
items
=
array
(
)
;
$
callbacks
=
array
(
)
;
foreach
(
$
reqs
as
$
req
)
{
$
items
[
]
=
$
req
[
2
]
;
$
callbacks
[
]
=
$
req
[
3
]
;
}
$
result
=
;
try
{
$
this
->
pcc_utilities
->
pubcall
(
$
uri
,
$
auth_header
,
$
items
)
;
$
result
=
array
(
true
,
''
)
;
}
catch
(
\
RuntimeException
$
exception
)
{
$
result
=
array
(
false
,
$
exception
->
getMessage
(
)
)
;
}
foreach
(
$
callbacks
as
$
callback
)
if
(
!
is_null
(
$
callback
)
)
{
call_user_func
(
$
callback
,
$
result
[
0
]
,
$
result
[
1
]
)
;
}
}


public function getKey( $cursor )
	{
		$this->calculateKeyMap();
		if( !array_key_exists( $cursor, $this->keyMap ) ) {
			return null;
		}

		return $this->keyMap[ $cursor ];
	}

public function getKey ( $ cursor ) { $ this -> calculateKeyMap ( ) ; if ( ! array_key_exists ( $ cursor , $ this -> keyMap ) ) { return null ; } return $ this -> keyMap [ $ cursor ] ; }

Returns key by given cursor position.

@param int $cursor The cursor position to check.

@return mixed


public function rewind()
	{
		$this->cursor = 0;
		$data         = $this->collection->getArrayCopy();
		reset( $data );
		$this->collection->exchangeArray( $data );

		return $this->current();
	}

public function rewind ( ) { $ this -> cursor = 0 ; $ data = $ this -> collection -> getArrayCopy ( ) ; reset ( $ data ) ; $ this -> collection -> exchangeArray ( $ data ) ; return $ this -> current ( ) ; }

Set the internal cursor to the first value in the array of data.

@return mixed

Set the internal cursor to the first value in the array of data .


public function export()
    {
        $format_types = array();
        foreach ($this->formats as $format)
        {
            $format_class_name = get_class($format);
            if (in_array($format_class_name, $format_types))
                throw new \RuntimeException('Multiple ' .
                        $format_class_name . ' format classes specified');
            array_push($format_types, $format_class_name);
        }
        $out = array();
        if (!is_null($this->id))
            $out['id'] = $this->id;
        if (!is_null($this->prev_id))
            $out['prev-id'] = $this->prev_id;
        foreach ($this->formats as $format)
            $out[$format->name()] = $format->export();
        return $out;
    }

public
function
export
(
)
{
$
format_types
=
array
(
)
;
foreach
(
$
this
->
formats
as
$
format
)
{
$
format_class_name
=
get_class
(
$
format
)
;
if
(
in_array
(
$
format_class_name
,
$
format_types
)
)
throw
new
\
RuntimeException
(
'Multiple '
.
$
format_class_name
.
' format classes specified'
)
;
array_push
(
$
format_types
,
$
format_class_name
)
;
}
$
out
=
array
(
)
;
if
(
!
is_null
(
$
this
->
id
)
)
$
out
[
'id'
]
=
$
this
->
id
;
if
(
!
is_null
(
$
this
->
prev_id
)
)
$
out
[
'prev-id'
]
=
$
this
->
prev_id
;
foreach
(
$
this
->
formats
as
$
format
)
$
out
[
$
format
->
name
(
)
]
=
$
format
->
export
(
)
;
return
$
out
;
}


public function setFromArray($options)
    {

        if ($options instanceof self) {
            $options = $options->toArray();
        }

        if (!is_array($options) && !$options instanceof Traversable) {
            throw new InvalidArgumentException(sprintf(
                'Parameter provided to %s must be an %s, %s or %s',
                __METHOD__,
                'array',
                'Traversable',
                'Zend\Stdlib\AbstractOptions'
            ));
        }

        foreach ($options as $key => $value) {
            $this->__set($key, $value);
        }

        return $this;
    }

Set one or more configuration properties

@param  array|Traversable|AbstractOptions $options
@throws InvalidArgumentException
@return AbstractOptions Provides fluent interface


public function pubcall($uri, $auth_header, $items)
    {
        $uri .= '/publish/';
        $content = array();
        $content['items'] = $items;
        $headers = array('Content-Type: application/json');
        if (!is_null($auth_header))
            $headers[] = 'Authorization: ' . $auth_header;
        $results = $this->make_http_request($uri, $headers, $content);
        $this->verify_http_status_code($results[0], $results[1]);
    }

public
function
pubcall
(
$
uri
,
$
auth_header
,
$
items
)
{
$
uri
.=
'/publish/'
;
$
content
=
array
(
)
;
$
content
[
'items'
]
=
$
items
;
$
headers
=
array
(
'Content-Type: application/json'
)
;
if
(
!
is_null
(
$
auth_header
)
)
$
headers
[
]
=
'Authorization: '
.
$
auth_header
;
$
results
=
$
this
->
make_http_request
(
$
uri
,
$
headers
,
$
content
)
;
$
this
->
verify_http_status_code
(
$
results
[
0
]
,
$
results
[
1
]
)
;
}


public function make_http_request($uri, $headers, $content)
    {
        $post = curl_init($uri);
        curl_setopt_array($post, array(
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_POSTFIELDS => json_encode($content)
        ));
        $response = curl_exec($post);
        if (curl_error($post) != '')
            throw new \RuntimeException('Failed to publish: ' .
                    curl_error($post));
        return array($response,
                intval(curl_getinfo($post, CURLINFO_HTTP_CODE)));
    }

public
function
make_http_request
(
$
uri
,
$
headers
,
$
content
)
{
$
post
=
curl_init
(
$
uri
)
;
curl_setopt_array
(
$
post
,
array
(
CURLOPT_POST
=>
true
,
CURLOPT_RETURNTRANSFER
=>
true
,
CURLOPT_HTTPHEADER
=>
$
headers
,
CURLOPT_POSTFIELDS
=>
json_encode
(
$
content
)
)
)
;
$
response
=
curl_exec
(
$
post
)
;
if
(
curl_error
(
$
post
)
!=
''
)
throw
new
\
RuntimeException
(
'Failed to publish: '
.
curl_error
(
$
post
)
)
;
return
array
(
$
response
,
intval
(
curl_getinfo
(
$
post
,
CURLINFO_HTTP_CODE
)
)
)
;
}

message with the specified URI, headers, and content.

message with the specified URI headers and content .


public function publish($channel, $item)
    {
        $export = $item->export();
        $export['channel'] = $channel;
        $uri = null;
        $auth = null;
        $uri = $this->uri;
        $auth = $this->pcc_utilities->gen_auth_header($this->auth_jwt_claim,
                $this->auth_jwt_key, $this->auth_basic_user,
                $this->auth_basic_pass);
        $this->pcc_utilities->pubcall($uri, $auth, array($export));
    }

public function publish ( $ channel , $ item ) { $ export = $ item -> export ( ) ; $ export [ 'channel' ] = $ channel ; $ uri = null ; $ auth = null ; $ uri = $ this -> uri ; $ auth = $ this -> pcc_utilities -> gen_auth_header ( $ this -> auth_jwt_claim , $ this -> auth_jwt_key , $ this -> auth_basic_user , $ this -> auth_basic_pass ) ; $ this -> pcc_utilities -> pubcall ( $ uri , $ auth , array ( $ export ) ) ; }

specified channel on the configured endpoint.

specified channel on the configured endpoint .


public function importHeaders(MessageInterface $from, $to)
    {
        foreach ($from->getHeaders() as $key => $headers) {
            foreach ($headers as $header) {
                $to->addHeader($key, $from->getHeaderLine($key));
            }
        }
    }

public function importHeaders ( MessageInterface $ from , $ to ) { foreach ( $ from -> getHeaders ( ) as $ key => $ headers ) { foreach ( $ headers as $ header ) { $ to -> addHeader ( $ key , $ from -> getHeaderLine ( $ key ) ) ; } } }

PSR-7 interfaces support multiple headers per type, whereas SilverStripe classes do not.

This method will assign headers as a comma delimited string from the PSR-7 interface to the SilverStripe class

@param MessageInterface         $from
@param HTTPRequest|HTTPResponse $to

PSR - 7 interfaces support multiple headers per type whereas SilverStripe classes do not .


public function getProtocolVersion()
    {
        if ($this->protocolVersion) {
            return $this->protocolVersion;
        }

        $protocolAndVersion = $_SERVER['SERVER_PROTOCOL'];
        list($protocol, $version) = explode('/', $protocolAndVersion);
        return $version;
    }

public function getProtocolVersion ( ) { if ( $ this -> protocolVersion ) { return $ this -> protocolVersion ; } $ protocolAndVersion = $ _SERVER [ 'SERVER_PROTOCOL' ] ; list ( $ protocol , $ version ) = explode ( '/' , $ protocolAndVersion ) ; return $ version ; }

Get the protocol version - either from a previously set value, or from the server

@return string E.g. "1.1"

Get the protocol version - either from a previously set value or from the server


protected function valid(array $data, array $rules, array $messages = [], array $aliases = [])
    {
        // load translate.
        $this->loadTranslate();

        $this->validation = $this->getValidator()->make($data, $rules, $messages);
        if (\count($aliases) > 0) {
            $this->setAliases($aliases);
        }
        $this->validation->setAliases($this->getAliases());
        $this->validation->validate();

        // if has custom invalid callback.
        if (\method_exists($this, 'InValidCallback') && $this->getValidation()->fails()) {
            return $this->InValidCallback($this->getValidation()->errors()->firstOfAll());
        }

        return !$this->getValidation()->fails();
    }

protected
function
valid
(
array
$
data
,
array
$
rules
,
array
$
messages
=
[
]
,
array
$
aliases
=
[
]
)
{
// load translate.
$
this
->
loadTranslate
(
)
;
$
this
->
validation
=
$
this
->
getValidator
(
)
->
make
(
$
data
,
$
rules
,
$
messages
)
;
if
(
\
count
(
$
aliases
)
>
0
)
{
$
this
->
setAliases
(
$
aliases
)
;
}
$
this
->
validation
->
setAliases
(
$
this
->
getAliases
(
)
)
;
$
this
->
validation
->
validate
(
)
;
// if has custom invalid callback.
if
(
\
method_exists
(
$
this
,
'InValidCallback'
)
&&
$
this
->
getValidation
(
)
->
fails
(
)
)
{
return
$
this
->
InValidCallback
(
$
this
->
getValidation
(
)
->
errors
(
)
->
firstOfAll
(
)
)
;
}
return
!
$
this
->
getValidation
(
)
->
fails
(
)
;
}

valid data.

@param array $data
@param array $rules
@param array $messages
@param array $aliases

@return mixed|\Rakit\Validation\Validation


protected function loadTranslate(): self
    {
        $this->getValidator()->setMessages($this->getTranslateLoader()->load($this->getValidatorLocal()));

        return $this;
    }

protected function loadTranslate ( ) : self { $ this -> getValidator ( ) -> setMessages ( $ this -> getTranslateLoader ( ) -> load ( $ this -> getValidatorLocal ( ) ) ) ; return $ this ; }


public function setValidatorLocal($local, $path = null): self
    {
        $this->validatorLocal = $local;

        if (!empty($path)) {
            $this->getTranslateLoader()->setPath($path);
        }

        return $this;
    }

public function setValidatorLocal ( $ local , $ path = null ) : self { $ this -> validatorLocal = $ local ; if ( ! empty ( $ path ) ) { $ this -> getTranslateLoader ( ) -> setPath ( $ path ) ; } return $ this ; }

set local of validation errors message.

@param string $local
@param null|string $path

@return HasValidator

set local of validation errors message .


protected function getValidErrors($firstOfAll = false)
    {
        return $firstOfAll ? $this->getValidation()->errors()->firstOfAll() : $this->getValidation()->errors();
    }

protected function getValidErrors ( $ firstOfAll = false ) { return $ firstOfAll ? $ this -> getValidation ( ) -> errors ( ) -> firstOfAll ( ) : $ this -> getValidation ( ) -> errors ( ) ; }

Get validation errors.

@param bool $firstOfAll

@return array|\Rakit\Validation\ErrorBag


public function update($num_calls, $callback)
    {
        $this->completed = false;
        $this->num_calls = $num_calls;
        $this->callback = $callback;
        $this->success = true;
    }

public function update ( $ num_calls , $ callback ) { $ this -> completed = false ; $ this -> num_calls = $ num_calls ; $ this -> callback = $ callback ; $ this -> success = true ; }

it with the specified num_calls and callback values.

it with the specified num_calls and callback values .


public function getLockedMessage()
    {
        $editor = $this->Editor();
        $editorString = $editor->getTitle();
        if ($editor->Email) {
            $editorString .= " <Email'>$editor->Email>";
        }
        $message = sprintf(
            _t('RecordBeingEdited.LOCKEDMESSAGE', 'Sorry, this %s is currently being edited by %s. To avoid conflicts and data loss, editing will be locked until they are finished.'),
            FormField::name_to_label($this->RecordClass),
            $editorString
        );

        if ($this->canEditAnyway()) {
            $editAnywayLink = Controller::join_links(Controller::curr()->getRequest()->requestVar('url'), '?editanyway=1');
            $message .= "";
            $message .= sprintf(_t('RecordBeingEdited.EDITANYWAY', 'I understand the risks, %s edit anyway %s'), "", "");
            $message .= "";
        }

        return $message;
    }

Generates the edit lock warning message displayed to the user
@return String


public function isEditingAnyway()
    {
        if (!$this->canEditAnyway()) {
            return false;
        }

        $sessionVar = 'EditAnyway_' . Member::currentUserID() . '_' . $this->ID;
        if (Controller::curr()->getRequest()->getVar('editanyway') == '1') {
            Session::set($sessionVar, true);
            return true;
        }
        return Session::get($sessionVar) ? true : false;
    }

public function isEditingAnyway ( ) { if ( ! $ this -> canEditAnyway ( ) ) { return false ; } $ sessionVar = 'EditAnyway_' . Member :: currentUserID ( ) . '_' . $ this -> ID ; if ( Controller :: curr ( ) -> getRequest ( ) -> getVar ( 'editanyway' ) == '1' ) { Session :: set ( $ sessionVar , true ) ; return true ; } return Session :: get ( $ sessionVar ) ? true : false ; }

Checks to see if the current user can and has elected to edit the record anyway
@return Boolaen


public function offsetExists( $offset )
	{
		// Can not retrieve a key based on a value other than a string, integer or boolean
		if( !is_string( $offset ) && !is_int( $offset ) && !is_bool( $offset ) ) {
			return false;
		}

		return array_key_exists( $offset, $this->data );
	}

Check if the given offset exists in the set of data.

@param mixed $offset The offset to check.

@return bool

Check if the given offset exists in the set of data .


public function usort( \Closure $callback )
	{
		usort( $this->data, $callback );
		reset( $this->data );

		return $this;
	}

public function usort ( \ Closure $ callback ) { usort ( $ this -> data , $ callback ) ; reset ( $ this -> data ) ; return $ this ; }

Provide a callback to use for sorting the data.

@param \Closure $callback The callback to be used.

@return $this

Provide a callback to use for sorting the data .


protected function parse(): void
    {
        list('year' => $year, 'month' => $month, 'day' => $day) = self::validate($this->birthday);
        $this->birthday = sprintf('%d-%02d-%02d', $year, $month, $day); // normalize the date
        $this->age = self::calculateAge($year, $month, $day);
        $this->constellation = self::parseConstellation($month, $day);
    }

protected
function
parse
(
)
:
void
{
list
(
'year'
=>
$
year
,
'month'
=>
$
month
,
'day'
=>
$
day
)
=
self
::
validate
(
$
this
->
birthday
)
;
$
this
->
birthday
=
sprintf
(
'%d-%02d-%02d'
,
$
year
,
$
month
,
$
day
)
;
// normalize the date
$
this
->
age
=
self
::
calculateAge
(
$
year
,
$
month
,
$
day
)
;
$
this
->
constellation
=
self
::
parseConstellation
(
$
month
,
$
day
)
;
}

Parse the birthday

@throws \InvalidArgumentException
@throws \OutOfRangeException


public function format($format = null): string
    {
        if (empty($format)) {
            return $this->birthday;
        }

        return date($format, strtotime($this->birthday));
    }

public function format ( $ format = null ) : string { if ( empty ( $ format ) ) { return $ this -> birthday ; } return date ( $ format , strtotime ( $ this -> birthday ) ) ; }

Return the birthday in given format

@param  string   $format
@return string


public static function validate($birthday): array
    {
        $date = strtotime($birthday);

        if ($date === false) {
            throw new \InvalidArgumentException("Invalid birthday: $birthday");
        }

        $year = date('Y', $date);
        $month = date('n', $date);
        $day = date('j', $date);
        $currentYear = date('Y');

        if ($year > $currentYear || $year <= $currentYear - self::MAX_AGE) {
            throw new \OutOfRangeException('The age is out of range [0, 200)');
        }

        return ['year' => $year, 'month' => $month, 'day' => $day];
    }

public
static
function
validate
(
$
birthday
)
:
array
{
$
date
=
strtotime
(
$
birthday
)
;
if
(
$
date
===
false
)
{
throw
new
\
InvalidArgumentException
(
"Invalid birthday: $birthday"
)
;
}
$
year
=
date
(
'Y'
,
$
date
)
;
$
month
=
date
(
'n'
,
$
date
)
;
$
day
=
date
(
'j'
,
$
date
)
;
$
currentYear
=
date
(
'Y'
)
;
if
(
$
year
>
$
currentYear
||
$
year
<=
$
currentYear
self
::
MAX_AGE
)
{
throw
new
\
OutOfRangeException
(
'The age is out of range [0, 200)'
)
;
}
return
[
'year'
=>
$
year
,
'month'
=>
$
month
,
'day'
=>
$
day
]
;
}

Validate birthday, if it is valid then return the birth year, month and day

@param  string                      $birthday
@throws \InvalidArgumentException
@throws \OutOfRangeException
@return array

Validate birthday if it is valid then return the birth year month and day


public static function parseConstellation($month, $day): string
    {
        switch ($month) {
            case 1:
                return $day >= 20 ? 'Aquarius' : 'Capricorn';
            case 2:
                return $day >= 19 ? 'Pisces' : 'Aquarius';
            case 3:
                return $day >= 21 ? 'Aries' : 'Pisces';
            case 4:
                return $day >= 20 ? 'Taurus' : 'Aries';
            case 5:
                return $day >= 21 ? 'Gemini' : 'Taurus';
            case 6:
                return $day >= 22 ? 'Cancer' : 'Gemini';
            case 7:
                return $day >= 23 ? 'Leo' : 'Cancer';
            case 8:
                return $day >= 23 ? 'Virgo' : 'Leo';
            case 9:
                return $day >= 23 ? 'Libra' : 'Virgo';
            case 10:
                return $day >= 24 ? 'Scorpio' : 'Libra';
            case 11:
                return $day >= 23 ? 'Sagittarius' : 'Scorpio';
            case 12:
                return $day >= 22 ? 'Capricorn' : 'Sagittarius';
        }
        throw new \InvalidArgumentException("Invalid month and day: $month , $day");
    }

public
static
function
parseConstellation
(
$
month
,
$
day
)
:
string
{
switch
(
$
month
)
{
case
1
:
return
$
day
>=
20
'Aquarius'
:
'Capricorn'
;
case
2
:
return
$
day
>=
19
'Pisces'
:
'Aquarius'
;
case
3
:
return
$
day
>=
21
'Aries'
:
'Pisces'
;
case
4
:
return
$
day
>=
20
'Taurus'
:
'Aries'
;
case
5
:
return
$
day
>=
21
'Gemini'
:
'Taurus'
;
case
6
:
return
$
day
>=
22
'Cancer'
:
'Gemini'
;
case
7
:
return
$
day
>=
23
'Leo'
:
'Cancer'
;
case
8
:
return
$
day
>=
23
'Virgo'
:
'Leo'
;
case
9
:
return
$
day
>=
23
'Libra'
:
'Virgo'
;
case
10
:
return
$
day
>=
24
'Scorpio'
:
'Libra'
;
case
11
:
return
$
day
>=
23
'Sagittarius'
:
'Scorpio'
;
case
12
:
return
$
day
>=
22
'Capricorn'
:
'Sagittarius'
;
}
throw
new
\
InvalidArgumentException
(
"Invalid month and day: $month , $day"
)
;
}

Parse constellation by the given month and day

@param  int                         $month
@param  int                         $day
@throws \InvalidArgumentException
@return string


protected function translate($constellation, $lang = 'en'): string
    {
        $arr = $this->loadTranslation($lang);

        return isset($arr[$constellation]) ? $arr[$constellation] : '';
    }

protected function translate ( $ constellation , $ lang = 'en' ) : string { $ arr = $ this -> loadTranslation ( $ lang ) ; return isset ( $ arr [ $ constellation ] ) ? $ arr [ $ constellation ] : '' ; }

Translate the constellation

@param  string   $constellation
@param  string   $lang
@return string


public function updateSucceed()
    {
        $this->synchronizer->handle();
        app('antares.memory')->make('component.default')->update();
        $message = trans('antares/acl::response.acls.update');
        return (app('request')->ajax()) ? Response::json(['message' => $message], 200) : $this->redirectWithMessage(handles("antares::acl/index/roles"), $message);
    }

public function updateSucceed ( ) { $ this -> synchronizer -> handle ( ) ; app ( 'antares.memory' ) -> make ( 'component.default' ) -> update ( ) ; $ message = trans ( 'antares/acl::response.acls.update' ) ; return ( app ( 'request' ) -> ajax ( ) ) ? Response :: json ( [ 'message' => $ message ] , 200 ) : $ this -> redirectWithMessage ( handles ( "antares::acl/index/roles" ) , $ message ) ; }

Response when ACL is updated.

@return mixed


public function syncSucceed(Fluent $acl)
    {
        $message = trans('antares/acl::response.acls.sync-roles', [
            'name' => $acl->get('name'),
        ]);

        return $this->redirectWithMessage(handles("antares::acl/acl?name={$acl->get('name')}"), $message);
    }

Response when sync roles succeed.

@param  \Illuminate\Support\Fluent   $acl

@return mixed


public function onList()
    {
        $this->onInit();
        Breadcrumbs::register('roles-list', function($breadcrumbs) {
            $breadcrumbs->parent('staff');
            $breadcrumbs->push(trans('antares/acl::title.breadcrumbs.groups'), handles('antares::acl/index/roles'));
        });
        view()->share('breadcrumbs', Breadcrumbs::render('roles-list'));
    }

public function onList ( ) { $ this -> onInit ( ) ; Breadcrumbs :: register ( 'roles-list' , function ( $ breadcrumbs ) { $ breadcrumbs -> parent ( 'staff' ) ; $ breadcrumbs -> push ( trans ( 'antares/acl::title.breadcrumbs.groups' ) , handles ( 'antares::acl/index/roles' ) ) ; } ) ; view ( ) -> share ( 'breadcrumbs' , Breadcrumbs :: render ( 'roles-list' ) ) ; }


public function onRoleCreateOrEdit(Model $model = null)
    {
        $this->onList();
        Breadcrumbs::register('edit-role', function($breadcrumbs) use($model) {
            $breadcrumbs->parent('roles-list');
            $exists = is_null($model) ? false : $model->exists;
            $name   = ($exists) ? 'Edit Group ' . $model->full_name : 'Add Group';
            $breadcrumbs->push($name, '#');
        });
        view()->share('breadcrumbs', Breadcrumbs::render('edit-role'));
    }

public
function
onRoleCreateOrEdit
(
Model
$
model
=
)
{
$
this
->
onList
(
)
;
Breadcrumbs
::
register
(
'edit-role'
,
function
(
$
breadcrumbs
)
use
(
$
model
)
{
$
breadcrumbs
->
parent
(
'roles-list'
)
;
$
exists
=
is_null
(
$
model
)
false
:
$
model
->
exists
;
$
name
=
(
$
exists
)
'Edit Group '
.
$
model
->
full_name
:
'Add Group'
;
$
breadcrumbs
->
push
(
$
name
,
'#'
)
;
}
)
;
view
(
)
->
share
(
'breadcrumbs'
,
Breadcrumbs
::
render
(
'edit-role'
)
)
;
}

on create or edit role

@param Model $model


public function onUserCreateOrEdit(Model $model)
    {
        $this->onUsersList();
        $name = $model->exists ? 'User Edit ' . $model->fullname : 'User Add';
        Breadcrumbs::register('user', function($breadcrumbs) use($name) {
            $breadcrumbs->parent('users-list');
            $breadcrumbs->push($name, '#');
        });
        view()->share('breadcrumbs', Breadcrumbs::render('user'));
    }

public
function
onUserCreateOrEdit
(
Model
$
model
)
{
$
this
->
onUsersList
(
)
;
$
name
=
$
model
->
exists
'User Edit '
.
$
model
->
fullname
:
'User Add'
;
Breadcrumbs
::
register
(
'user'
,
function
(
$
breadcrumbs
)
use
(
$
name
)
{
$
breadcrumbs
->
parent
(
'users-list'
)
;
$
breadcrumbs
->
push
(
$
name
,
'#'
)
;
}
)
;
view
(
)
->
share
(
'breadcrumbs'
,
Breadcrumbs
::
render
(
'user'
)
)
;
}

on user create or edit

@param Model $model


public function onAreaCreate()
    {
        $this->onAreasList();
        Breadcrumbs::register('area-create', function($breadcrumbs) {
            $breadcrumbs->parent('areas-list');
            $breadcrumbs->push(trans('antares/acl::messages.area_add'), '#');
        });
        view()->share('breadcrumbs', Breadcrumbs::render('area-create'));
    }

public function onAreaCreate ( ) { $ this -> onAreasList ( ) ; Breadcrumbs :: register ( 'area-create' , function ( $ breadcrumbs ) { $ breadcrumbs -> parent ( 'areas-list' ) ; $ breadcrumbs -> push ( trans ( 'antares/acl::messages.area_add' ) , '#' ) ; } ) ; view ( ) -> share ( 'breadcrumbs' , Breadcrumbs :: render ( 'area-create' ) ) ; }


public function form($model)
    {
        $this->breadcrumb->onUserCreateOrEdit($model);
        return $this->form->of('antares.users', function (FormGrid $form) use ($model) {
                    $form->name('user.form');
                    $form->resource($this, 'antares::acl/index/users', $model);
                    $form->hidden('id');
                    $form->fieldset('User fields', function (Fieldset $fieldset) use($model) {
                        $fieldset->control('input:text', 'email')
                                ->label(trans('antares/foundation::label.users.email'));

                        $fieldset->control('input:text', 'firstname')
                                ->label(trans('antares/foundation::label.users.firstname'));

                        $fieldset->control('input:text', 'lastname')
                                ->label(trans('antares/foundation::label.users.lastname'));

                        $fieldset->control('input:password', 'password')
                                ->label(trans('antares/foundation::label.users.password'));

                        if ($model->id != user()->id) {
                            $status = $fieldset->control('input:checkbox', 'status')
                                    ->label(trans('antares/foundation::label.users.active'))
                                    ->value(1);
                            if ($model->status) {
                                $status->checked();
                            }
                        }

                        $fieldset->control('select', 'roles[]')
                                ->label(trans('antares/foundation::label.users.roles'))
                                ->options(function () {
                                    $roles = app('antares.role');
                                    if (config('antares/acl::allow_register_with_other_roles')) {
                                        return $roles->managers()->pluck('name', 'id');
                                    } else {
                                        return user()->roles->pluck('name', 'id');
                                    }
                                })
                                ->value(function ($row) {
                                    $roles = [];
                                    foreach ($row->roles as $row) {
                                        $roles[] = $row->id;
                                    }
                                    return $roles;
                                });
                        $fieldset->control('button', 'button')
                                ->attributes(['type' => 'submit', 'class' => 'btn btn--md btn--primary mdl-button mdl-js-button mdl-js-ripple-effect'])
                                ->value(trans('antares/foundation::label.save_changes'));

                        $fieldset->control('button', 'cancel')
                                ->field(function() {
                                    return app('html')->link(handles("antares::acl/index/users"), trans('antares/foundation::label.cancel'), ['class' => 'btn btn--md btn--default mdl-button mdl-js-button']);
                                });
                    });
                    $form->rules([
                        'email'     => ['required', 'email', 'unique:tbl_users,email' . ((!$model->exists) ? '' : ',' . $model->id)],
                        'firstname' => ['required'],
                        'lastname'  => ['required'],
                        'roles'     => ['required'],
                    ]);
                });
    }

Form View Generator for Antares\Model\User.

@param  User  $model

@return Builder

Form View Generator for Antares \ Model \ User .


public function handle()
    {
        $acl           = app('antares.acl')->make('antares/acl');
        $canCreateRole = $acl->can('create-role');
        if (!$canCreateRole) {
            return;
        }
        $this->createMenu();

        if ($canCreateRole) {
            $this->handler
                    ->add('role-add', '^:roles')
                    ->title('Add Group')
                    ->icon('zmdi-plus-circle-o')
                    ->link(handles('antares::acl/index/roles/create'));
        }
    }

public
function
handle
(
)
{
$
acl
=
app
(
'antares.acl'
)
->
make
(
'antares/acl'
)
;
$
canCreateRole
=
$
acl
->
can
(
'create-role'
)
;
if
(
!
$
canCreateRole
)
{
return
;
}
$
this
->
createMenu
(
)
;
if
(
$
canCreateRole
)
{
$
this
->
handler
->
add
(
'role-add'
,
'^:roles'
)
->
title
(
'Add Group'
)
->
icon
(
'zmdi-plus-circle-o'
)
->
link
(
handles
(
'antares::acl/index/roles/create'
)
)
;
}
}


public function findOneByOrGetNew(array $criteria)
    {
        $object = $this->findOneBy($criteria);

        if ($object === null) {
            $object = $this->getNew();
        }

        return $object;
    }

public function findOneByOrGetNew ( array $ criteria ) { $ object = $ this -> findOneBy ( $ criteria ) ; if ( $ object === null ) { $ object = $ this -> getNew ( ) ; } return $ object ; }

Find one object by a set of criteria or create a new one.

@param array $criteria

@throws \RuntimeException

@return object

Find one object by a set of criteria or create a new one .


public function getNew()
    {
        $object = \call_user_func($this->getObjectFactory());

        if (!$this->canBeManaged($object)) {
            throw new \RuntimeException(
                \sprintf(
                    'Object factory must return an instance of %s. "%s" returned',
                    $this->getClassName(),
                    \is_object($object) ? \get_class($object) : \gettype($object)
                )
            );
        }

        return $object;
    }

Get a new managed object instance.

@throws \RuntimeException

@return object


private function getObjectFactory(): callable
    {
        if ($this->objectFactory === null) {
            $className = $this->getClassName();

            $this->objectFactory = function () use ($className) {
                return new $className();
            };
        }

        return $this->objectFactory;
    }

private function getObjectFactory ( ) : callable { if ( $ this -> objectFactory === null ) { $ className = $ this -> getClassName ( ) ; $ this -> objectFactory = function ( ) use ( $ className ) { return new $ className ( ) ; } ; } return $ this -> objectFactory ; }


public function removeBy(array $criteria, bool $flush = false)
    {
        $this->runManagerAction('remove', $this->findBy($criteria), $flush);
    }

public function removeBy ( array $ criteria , bool $ flush = false ) { $ this -> runManagerAction ( 'remove' , $ this -> findBy ( $ criteria ) , $ flush ) ; }

Remove object filtered by a set of criteria.

@param array $criteria
@param bool  $flush

Remove object filtered by a set of criteria .


public function removeOneBy(array $criteria, bool $flush = false)
    {
        $this->runManagerAction('remove', $this->findOneBy($criteria), $flush);
    }

public function removeOneBy ( array $ criteria , bool $ flush = false ) { $ this -> runManagerAction ( 'remove' , $ this -> findOneBy ( $ criteria ) , $ flush ) ; }

Remove first object filtered by a set of criteria.

@param array $criteria
@param bool  $flush

Remove first object filtered by a set of criteria .


public function remove($objects, bool $flush = false)
    {
        if (!\is_object($objects) && !is_iterable($objects)) {
            $objects = $this->find($objects);
        }

        $this->runManagerAction('remove', $objects, $flush);
    }

public function remove ( $ objects , bool $ flush = false ) { if ( ! \ is_object ( $ objects ) && ! is_iterable ( $ objects ) ) { $ objects = $ this -> find ( $ objects ) ; } $ this -> runManagerAction ( 'remove' , $ objects , $ flush ) ; }

Remove objects.

@param object|iterable|string|int $objects
@param bool                       $flush

@throws \InvalidArgumentException


public function refresh($objects)
    {
        $backupAutoFlush = $this->autoFlush;

        $this->autoFlush = false;
        $this->runManagerAction('refresh', $objects, false);

        $this->autoFlush = $backupAutoFlush;
    }

public function refresh ( $ objects ) { $ backupAutoFlush = $ this -> autoFlush ; $ this -> autoFlush = false ; $ this -> runManagerAction ( 'refresh' , $ objects , false ) ; $ this -> autoFlush = $ backupAutoFlush ; }

Refresh objects.

@param object|iterable $objects

@throws \InvalidArgumentException


public function detach($objects)
    {
        $backupAutoFlush = $this->autoFlush;

        $this->autoFlush = false;
        $this->runManagerAction('detach', $objects, false);

        $this->autoFlush = $backupAutoFlush;
    }

public function detach ( $ objects ) { $ backupAutoFlush = $ this -> autoFlush ; $ this -> autoFlush = false ; $ this -> runManagerAction ( 'detach' , $ objects , false ) ; $ this -> autoFlush = $ backupAutoFlush ; }

Detach objects.

@param object|iterable $objects

@throws \InvalidArgumentException


private function getSupportedMethod(string $method): string
    {
        foreach (static::$supportedMethods as $supportedMethod) {
            if (\strpos($method, $supportedMethod) === 0) {
                return $supportedMethod;
            }
        }

        throw new \BadMethodCallException(\sprintf(
            'Undefined method "%s". Method call must start with one of "%s"!',
            $method,
            \implode('", "', static::$supportedMethods)
        ));
    }

Get supported magic method.

@param string $method

@throws \BadMethodCallException

@return string


protected function callSupportedMethod(string $method, string $fieldName, array $arguments)
    {
        $classMetadata = $this->getClassMetadata();

        if (!$classMetadata->hasField($fieldName) && !$classMetadata->hasAssociation($fieldName)) {
            throw new \BadMethodCallException(\sprintf(
                'Invalid call to %s::%s. Field "%s" does not exist',
                $this->getClassName(),
                $method,
                $fieldName
            ));
        }

        // @codeCoverageIgnoreStart
        $parameters = \array_merge(
            [$fieldName => $arguments[0]],
            \array_slice($arguments, 1)
        );

        return \call_user_func_array([$this, $method], $parameters);
        // @codeCoverageIgnoreEnd
    }

Internal method call.

@param string $method
@param string $fieldName
@param array  $arguments

@throws \BadMethodCallException

@return mixed


protected function runManagerAction(string $action, $objects, bool $flush)
    {
        $manager = $this->getManager();

        if (!is_iterable($objects)) {
            $objects = \array_filter([$objects]);
        }

        foreach ($objects as $object) {
            if (!$this->canBeManaged($object)) {
                throw new \InvalidArgumentException(
                    \sprintf(
                        'Managed object must be a %s. "%s" given',
                        $this->getClassName(),
                        \is_object($object) ? \get_class($object) : \gettype($object)
                    )
                );
            }

            $manager->$action($object);
        }

        // @codeCoverageIgnoreStart
        if ($objects instanceof \Traversable) {
            $objects = \iterator_to_array($objects);
        }
        // @codeCoverageIgnoreEnd

        $this->flushObjects($objects, $flush);
    }

Run manager action.

@param string          $action
@param object|iterable $objects
@param bool            $flush

@throws \InvalidArgumentException


protected function flushObjects(array $objects, bool $flush)
    {
        if ($flush || $this->autoFlush) {
            $this->getManager()->flush($objects);
        }
    }

protected function flushObjects ( array $ objects , bool $ flush ) { if ( $ flush || $ this -> autoFlush ) { $ this -> getManager ( ) -> flush ( $ objects ) ; } }

Flush managed objects.

@param array $objects
@param bool  $flush


protected function prepareTagFromBits($additional_identifier, $visitor_identifier, $hash)
    {
        return implode(',', [$this->getApplicationIdentifier(), 'collection', get_class($this), $additional_identifier, $visitor_identifier, $hash]);
    }

protected function prepareTagFromBits ( $ additional_identifier , $ visitor_identifier , $ hash ) { return implode ( ',' , [ $ this -> getApplicationIdentifier ( ) , 'collection' , get_class ( $ this ) , $ additional_identifier , $ visitor_identifier , $ hash ] ) ; }

Prepare collection tag from bits of information.

@param  string $additional_identifier
@param  string $visitor_identifier
@param  string $hash
@return string

Prepare collection tag from bits of information .


public function &pagination($current_page = 1, $items_per_page = 100)
    {
        $this->is_paginated = true;

        $this->currentPage($current_page);

        $this->items_per_page = (int) $items_per_page;

        if ($this->items_per_page < 1) {
            $this->items_per_page = 100;
        }

        return $this;
    }

public function & pagination ( $ current_page = 1 , $ items_per_page = 100 ) { $ this -> is_paginated = true ; $ this -> currentPage ( $ current_page ) ; $ this -> items_per_page = ( int ) $ items_per_page ; if ( $ this -> items_per_page < 1 ) { $ this -> items_per_page = 100 ; } return $ this ; }

Set pagination configuration.

@param  int   $current_page
@param  int   $items_per_page
@return $this


public function &currentPage($value)
    {
        if (!$this->is_paginated) {
            throw new LogicException('Page can be set only for paginated collections');
        }

        $this->current_page = (int) $value;

        if ($this->current_page < 1) {
            $this->current_page = 1;
        }

        return $this;
    }

Set current page.

@param  int   $value
@return $this


public function update(PermissionRequest $request, $id)
    {
        $this->authorize('edit_permission');
        $permission = Permissions::where('id', $id)->firstOrFail();
        $permission->update($request->all());
        $request->session()->flash('message', 'Permission Updated Successfully');
        return redirect()->route('RoleManager::permission.edit', $permission->id);
    }

public
function
update
(
PermissionRequest
$
request
,
$
id
)
{
$
this
->
authorize
(
'edit_permission'
)
;
$
permission
=
Permissions
::
where
(
'id'
,
$
id
)
->
firstOrFail
(
)
;
$
permission
->
update
(
$
request
->
all
(
)
)
;
$
request
->
session
(
)
->
flash
(
'message'
,
'Permission Updated Successfully'
)
;
return
redirect
(
)
->
route
(
'RoleManager::permission.edit'
,
$
permission
->
id
)
;
}

Update the permission in storage.

@param Request|PermissionRequest $request
@param int                       $id

@return \Illuminate\Http\Response


protected function getPaginator(AdapterInterface $adapter, int $itemsPerPage): Paginator
    {
        $paginator = new Paginator($adapter);
        $paginator->setItemCountPerPage(max(-1, $itemsPerPage));

        return $paginator;
    }

protected function getPaginator ( AdapterInterface $ adapter , int $ itemsPerPage ) : Paginator { $ paginator = new Paginator ( $ adapter ) ; $ paginator -> setItemCountPerPage ( max ( - 1 , $ itemsPerPage ) ) ; return $ paginator ; }

Get configured paginator.

@param AdapterInterface $adapter
@param int              $itemsPerPage

@return Paginator


public function findPaginatedByOrFail(array $criteria, array $orderBy = null, int $itemsPerPage = 10): Paginator
    {
        $paginator = $this->findPaginatedBy($criteria, $orderBy, $itemsPerPage);

        if ($paginator->count() === 0) {
            throw new FindException('FindPaginatedBy did not return any results');
        }

        return $paginator;
    }

Return paginated elements filtered by criteria or throw an exception if none found.

@param array      $criteria
@param array|null $orderBy
@param int        $itemsPerPage

@throws FindException

@return Paginator

Return paginated elements filtered by criteria or throw an exception if none found .


protected function bootExtensionComponents()
    {
        $path = __DIR__ . '/../resources';
        $this->addConfigComponent('antares/acl', 'antares/acl', "{$path}/config");
        $this->addLanguageComponent('antares/acl', 'antares/acl', "{$path}/lang");
        $this->addViewComponent('antares/acl', 'antares/acl', "{$path}/views");
        $this->bootMenu();
        $this->bootMemory();
    }

protected function bootExtensionComponents ( ) { $ path = __DIR__ . '/../resources' ; $ this -> addConfigComponent ( 'antares/acl' , 'antares/acl' , "{$path}/config" ) ; $ this -> addLanguageComponent ( 'antares/acl' , 'antares/acl' , "{$path}/lang" ) ; $ this -> addViewComponent ( 'antares/acl' , 'antares/acl' , "{$path}/views" ) ; $ this -> bootMenu ( ) ; $ this -> bootMemory ( ) ; }

Boot extension components.

@return void


protected function bootMemory()
    {
        $this->app->make('antares.acl')->make($this->routeGroup)->attach(
                $this->app->make('antares.platform.memory')
        );
    }

protected function bootMemory ( ) { $ this -> app -> make ( 'antares.acl' ) -> make ( $ this -> routeGroup ) -> attach ( $ this -> app -> make ( 'antares.platform.memory' ) ) ; }


private function _loadParts()
    {
        $this->loadRoutesFrom(__DIR__ . '/routes.php');
        $this->loadMigrationsFrom(__DIR__ . '/migrations');
        $this->loadTranslationsFrom(__DIR__ . '/translations', 'RoleManager');
        $this->loadViewsFrom(__DIR__ . '/views', 'RoleManager');
    }

private function _loadParts ( ) { $ this -> loadRoutesFrom ( __DIR__ . '/routes.php' ) ; $ this -> loadMigrationsFrom ( __DIR__ . '/migrations' ) ; $ this -> loadTranslationsFrom ( __DIR__ . '/translations' , 'RoleManager' ) ; $ this -> loadViewsFrom ( __DIR__ . '/views' , 'RoleManager' ) ; }


private function _extendedValidation()
    {
        Validator::extend(
            'classExist', function ($attribute, $value, $parameters, $validator) {
                if (empty($value)) {
                    return true;
                }
                return class_exists($value);
            }
        );
        Validator::extend(
            'methodExist', function ($attribute, $value, $parameters, $validator) {
                if (!empty(Request::input('class'))) {
                    return method_exists(Request::input('class'), $value);
                }
                return true;
            }
        );

        Validator::replacer(
            'classExist',
            function ($message, $attribute, $rule, $parameters) {
                return "Class does not exist";
            }
        );
        Validator::replacer(
            'methodExist',
            function ($message, $attribute, $rule, $parameters) {
                return
                    "Method in "
                    . Request::input('class')
                    . " class does not exist.";
            }
        );
    }

private
function
_extendedValidation
(
)
{
Validator
::
extend
(
'classExist'
,
function
(
$
attribute
,
$
value
,
$
parameters
,
$
validator
)
{
if
(
empty
(
$
value
)
)
{
return
true
;
}
return
class_exists
(
$
value
)
;
}
)
;
Validator
::
extend
(
'methodExist'
,
function
(
$
attribute
,
$
value
,
$
parameters
,
$
validator
)
{
if
(
!
empty
(
Request
::
input
(
'class'
)
)
)
{
return
method_exists
(
Request
::
input
(
'class'
)
,
$
value
)
;
}
return
true
;
}
)
;
Validator
::
replacer
(
'classExist'
,
function
(
$
message
,
$
attribute
,
$
rule
,
$
parameters
)
{
return
"Class does not exist"
;
}
)
;
Validator
::
replacer
(
'methodExist'
,
function
(
$
message
,
$
attribute
,
$
rule
,
$
parameters
)
{
return
"Method in "
.
Request
::
input
(
'class'
)
.
" class does not exist."
;
}
)
;
}


public function save(array $new_attributes = array(), $forceSave = false)
    {
        $options = array();

        if (array_key_exists('touch', $new_attributes))
        {
            $options['touch'] = $new_attributes['touch'];
            $new_attributes = array_except($new_attributes, array('touch'));
        }

        $this->fill($new_attributes);

        $this->beforeSave();

        if (! $forceSave)
        {
            // If the validation failed, return false
            if (! $this->valid && ! $this->validate())
                return false;
        }

        // Purge unnecessary fields
        $this->purgeUnneeded();

        // Auto hash passwords
        $this->autoHash();

        $this->saved = true;

        return parent::save($options);
    }

Prepare before the Model is actually saved

@param array $new_attributes New attributes to fill onto the model before saving
@param bool  $forceSave      Whether to validate or not. Defaults to validating before saving

@return bool


public function validate()
    {
        // Merge the rules arrays into one array
        $this->mergeRules();

        // Exclude this object from unique checks if object exists
        if ($this->exists)
        {
            $this->excludeFromUniqueChecks();
        }

        $validation = Validator::make($this->attributes, $this->mergedRules, $this->customMessages);

        // Sets the connection, based on the model's connection variable.
        $validation->getPresenceVerifier()->setConnection($this->connection);

        // Set custom messages on validator
        $validation->setAttributeNames($this->niceNames());

        if ($validation->passes())
        {
            $this->valid = true;

            return true;
        }

        $this->validationErrors = $validation->messages();

        return false;
    }

Performs validation on the model and return whether it
passed or failed

@return bool


protected function mergeRules()
    {
        $rules = static::$rules;
        $output = array();

        if ($this->exists)
            $merged = array_merge_recursive($rules['save'], $rules['update']);
        else
            $merged = array_merge_recursive($rules['save'], $rules['create']);

        foreach ($merged as $field => $rules)
        {
            if (is_array($rules))
                $output[$field] = implode("|", $rules);
            else
                $output[$field] = $rules;
        }

        $this->mergedRules = $output;
    }

protected function mergeRules ( ) { $ rules = static :: $ rules ; $ output = array ( ) ; if ( $ this -> exists ) $ merged = array_merge_recursive ( $ rules [ 'save' ] , $ rules [ 'update' ] ) ; else $ merged = array_merge_recursive ( $ rules [ 'save' ] , $ rules [ 'create' ] ) ; foreach ( $ merged as $ field => $ rules ) { if ( is_array ( $ rules ) ) $ output [ $ field ] = implode ( "|" , $ rules ) ; else $ output [ $ field ] = $ rules ; } $ this -> mergedRules = $ output ; }

Merges saving validation rules in with create and update rules
to allow rules to differ on create and update.

@return array

Merges saving validation rules in with create and update rules to allow rules to differ on create and update .


private function purgeUnneeded()
    {
        $clean = array();
        foreach ($this->attributes as $key => $value)
        {
            if (! Str::endsWith($key, '_confirmation') && ! Str::startsWith($key, '_') && ! in_array($key, static::$purgeable))
                $clean[$key] = $value;
        }
        $this->attributes = $clean;
    }

private function purgeUnneeded ( ) { $ clean = array ( ) ; foreach ( $ this -> attributes as $ key => $ value ) { if ( ! Str :: endsWith ( $ key , '_confirmation' ) && ! Str :: startsWith ( $ key , '_' ) && ! in_array ( $ key , static :: $ purgeable ) ) $ clean [ $ key ] = $ value ; } $ this -> attributes = $ clean ; }

Purges unneeded fields by getting rid of all attributes
ending in '_confirmation' or starting with '_'

@return array

Purges unneeded fields by getting rid of all attributes ending in _confirmation or starting with _


private function autoHash()
    {
        $attributes = array_merge(static::$needsHash, array('password'));

        foreach ($attributes as $name) {

            if (isset($this->attributes[$name]) && $this->isDirty($name))
            {
                if ( ! Hash::check($this->attributes[$name], $this->getOriginal($name)))
                {
                    $this->attributes[$name] = Hash::make($this->attributes[$name]);
                }
            }
        }
    }

private function autoHash ( ) { $ attributes = array_merge ( static :: $ needsHash , array ( 'password' ) ) ; foreach ( $ attributes as $ name ) { if ( isset ( $ this -> attributes [ $ name ] ) && $ this -> isDirty ( $ name ) ) { if ( ! Hash :: check ( $ this -> attributes [ $ name ] , $ this -> getOriginal ( $ name ) ) ) { $ this -> attributes [ $ name ] = Hash :: make ( $ this -> attributes [ $ name ] ) ; } } } }

Auto-hashes the password parameter if it exists

@return array

Auto - hashes the password parameter if it exists


public function disableFilters()
    {
        foreach (\array_keys($this->getFilterCollection()->getEnabledFilters()) as $filter) {
            $this->disableFilter($filter);
        }
    }

public function disableFilters ( ) { foreach ( \ array_keys ( $ this -> getFilterCollection ( ) -> getEnabledFilters ( ) ) as $ filter ) { $ this -> disableFilter ( $ filter ) ; } }


public function disableFilter(string $filter)
    {
        if (\in_array($filter, $this->disabledFilters, true)) {
            return;
        }

        $this->getFilterCollection()->disable($filter);

        $this->disabledFilters[] = $filter;
    }

public function disableFilter ( string $ filter ) { if ( \ in_array ( $ filter , $ this -> disabledFilters , true ) ) { return ; } $ this -> getFilterCollection ( ) -> disable ( $ filter ) ; $ this -> disabledFilters [ ] = $ filter ; }


public function restoreFilters()
    {
        $filterCollection = $this->getFilterCollection();

        foreach ($this->disabledFilters as $filter) {
            $filterCollection->enable($filter);
        }

        $this->disabledFilters = [];
    }

public function restoreFilters ( ) { $ filterCollection = $ this -> getFilterCollection ( ) ; foreach ( $ this -> disabledFilters as $ filter ) { $ filterCollection -> enable ( $ filter ) ; } $ this -> disabledFilters = [ ] ; }


public function restoreFilter(string $filter)
    {
        $position = \array_search($filter, $this->disabledFilters, true);
        if ($position === false) {
            return;
        }

        $this->getFilterCollection()->enable($filter);

        \array_splice($this->disabledFilters, $position, 1);
    }

public function restoreFilter ( string $ filter ) { $ position = \ array_search ( $ filter , $ this -> disabledFilters , true ) ; if ( $ position === false ) { return ; } $ this -> getFilterCollection ( ) -> enable ( $ filter ) ; \ array_splice ( $ this -> disabledFilters , $ position , 1 ) ; }

Restore disabled filter.

@param string $filter