public function addUpload(
        $fieldName, $filename, $sendFilename = null, $contentType = null
    ) {
        if (!is_array($filename)) {
            $fileData = $this->fopenWrapper($filename, empty($contentType));
            $this->uploads[$fieldName] = array(
                'fp'        => $fileData['fp'],
                'filename'  => !empty($sendFilename)? $sendFilename
                                :(is_string($filename)? basename($filename): 'anonymous.blob') ,
                'size'      => $fileData['size'],
                'type'      => empty($contentType)? $fileData['type']: $contentType
            );
        } else {
            $fps = $names = $sizes = $types = array();
            foreach ($filename as $f) {
                if (!is_array($f)) {
                    $f = array($f);
                }
                $fileData = $this->fopenWrapper($f[0], empty($f[2]));
                $fps[]   = $fileData['fp'];
                $names[] = !empty($f[1])? $f[1]
                            :(is_string($f[0])? basename($f[0]): 'anonymous.blob');
                $sizes[] = $fileData['size'];
                $types[] = empty($f[2])? $fileData['type']: $f[2];
            }
            $this->uploads[$fieldName] = array(
                'fp' => $fps, 'filename' => $names, 'size' => $sizes, 'type' => $types
            );
        }
        if (empty($this->headers['content-type'])
            || 'application/x-www-form-urlencoded' == $this->headers['content-type']
        ) {
            $this->setHeader('content-type', 'multipart/form-data');
        }

        return $this;
    }

public function addUpload ( $ fieldName , $ filename , $ sendFilename = null , $ contentType = null ) { if ( ! is_array ( $ filename ) ) { $ fileData = $ this -> fopenWrapper ( $ filename , empty ( $ contentType ) ) ; $ this -> uploads [ $ fieldName ] = array ( 'fp' => $ fileData [ 'fp' ] , 'filename' => ! empty ( $ sendFilename ) ? $ sendFilename : ( is_string ( $ filename ) ? basename ( $ filename ) : 'anonymous.blob' ) , 'size' => $ fileData [ 'size' ] , 'type' => empty ( $ contentType ) ? $ fileData [ 'type' ] : $ contentType ) ; } else { $ fps = $ names = $ sizes = $ types = array ( ) ; foreach ( $ filename as $ f ) { if ( ! is_array ( $ f ) ) { $ f = array ( $ f ) ; } $ fileData = $ this -> fopenWrapper ( $ f [ 0 ] , empty ( $ f [ 2 ] ) ) ; $ fps [ ] = $ fileData [ 'fp' ] ; $ names [ ] = ! empty ( $ f [ 1 ] ) ? $ f [ 1 ] : ( is_string ( $ f [ 0 ] ) ? basename ( $ f [ 0 ] ) : 'anonymous.blob' ) ; $ sizes [ ] = $ fileData [ 'size' ] ; $ types [ ] = empty ( $ f [ 2 ] ) ? $ fileData [ 'type' ] : $ f [ 2 ] ; } $ this -> uploads [ $ fieldName ] = array ( 'fp' => $ fps , 'filename' => $ names , 'size' => $ sizes , 'type' => $ types ) ; } if ( empty ( $ this -> headers [ 'content-type' ] ) || 'application/x-www-form-urlencoded' == $ this -> headers [ 'content-type' ] ) { $ this -> setHeader ( 'content-type' , 'multipart/form-data' ) ; } return $ this ; }

Adds a file to form-based file upload

Used to emulate file upload via a HTML form. The method also sets
Content-Type of HTTP request to 'multipart/form-data'.

If you just want to send the contents of a file as the body of HTTP
request you should use setBody() method.

If you provide file pointers rather than file names, they should support
fstat() and rewind() operations.

@param string                $fieldName    name of file-upload field
@param string|resource|array $filename     full name of local file,
pointer to open file or an array of files
@param string                $sendFilename filename to send in the request
@param string                $contentType  content-type of file being uploaded

@return   HTTP_Request2
@throws   HTTP_Request2_LogicException


public function attach(SplObserver $observer)
    {
        foreach ($this->observers as $attached) {
            if ($attached === $observer) {
                return;
            }
        }
        $this->observers[] = $observer;
    }

public function attach ( SplObserver $ observer ) { foreach ( $ this -> observers as $ attached ) { if ( $ attached === $ observer ) { return ; } } $ this -> observers [ ] = $ observer ; }

Attaches a new observer

@param SplObserver $observer any object implementing SplObserver


public function detach(SplObserver $observer)
    {
        foreach ($this->observers as $key => $attached) {
            if ($attached === $observer) {
                unset($this->observers[$key]);
                return;
            }
        }
    }

public function detach ( SplObserver $ observer ) { foreach ( $ this -> observers as $ key => $ attached ) { if ( $ attached === $ observer ) { unset ( $ this -> observers [ $ key ] ) ; return ; } } }

Detaches an existing observer

@param SplObserver $observer any object implementing SplObserver


public function setLastEvent($name, $data = null)
    {
        $this->lastEvent = array(
            'name' => $name,
            'data' => $data
        );
        $this->notify();
    }

public function setLastEvent ( $ name , $ data = null ) { $ this -> lastEvent = array ( 'name' => $ name , 'data' => $ data ) ; $ this -> notify ( ) ; }

Sets the last event

Adapters should use this method to set the current state of the request
and notify the observers.

@param string $name event name
@param mixed  $data event data


public function setAdapter($adapter)
    {
        if (is_string($adapter)) {
            if (!class_exists($adapter, false)) {
                if (false === strpos($adapter, '_')) {
                    $adapter = 'HTTP_Request2_Adapter_' . ucfirst($adapter);
                }
                if (!class_exists($adapter, false)
                    && preg_match('/^HTTP_Request2_Adapter_([a-zA-Z0-9]+)$/', $adapter)
                ) {
                    include_once str_replace('_', DIRECTORY_SEPARATOR, $adapter) . '.php';
                }
                if (!class_exists($adapter, false)) {
                    throw new HTTP_Request2_LogicException(
                        "Class {$adapter} not found",
                        HTTP_Request2_Exception::MISSING_VALUE
                    );
                }
            }
            $adapter = new $adapter;
        }
        if (!$adapter instanceof HTTP_Request2_Adapter) {
            throw new HTTP_Request2_LogicException(
                'Parameter is not a HTTP request adapter',
                HTTP_Request2_Exception::INVALID_ARGUMENT
            );
        }
        $this->adapter = $adapter;

        return $this;
    }

Sets the adapter used to actually perform the request

You can pass either an instance of a class implementing HTTP_Request2_Adapter
or a class name. The method will only try to include a file if the class
name starts with HTTP_Request2_Adapter_, it will also try to prepend this
prefix to the class name if it doesn't contain any underscores, so that
<code>
$request->setAdapter('curl');
</code>
will work.

@param string|HTTP_Request2_Adapter $adapter Adapter to use

@return   HTTP_Request2
@throws   HTTP_Request2_LogicException


public function setCookieJar($jar = true)
    {
        if (!class_exists('HTTP_Request2_CookieJar', false)) {
            require_once 'HTTP/Request2/CookieJar.php';
        }

        if ($jar instanceof HTTP_Request2_CookieJar) {
            $this->cookieJar = $jar;
        } elseif (true === $jar) {
            $this->cookieJar = new HTTP_Request2_CookieJar();
        } elseif (!$jar) {
            $this->cookieJar = null;
        } else {
            throw new HTTP_Request2_LogicException(
                'Invalid parameter passed to setCookieJar()',
                HTTP_Request2_Exception::INVALID_ARGUMENT
            );
        }

        return $this;
    }

Sets the cookie jar

A cookie jar is used to maintain cookies across HTTP requests and
responses. Cookies from jar will be automatically added to the request
headers based on request URL.

@param HTTP_Request2_CookieJar|bool $jar Existing CookieJar object, true to
create a new one, false to remove

@return HTTP_Request2
@throws HTTP_Request2_LogicException


public function send()
    {
        // Sanity check for URL
        if (!$this->url instanceof Net_URL2
            || !$this->url->isAbsolute()
            || !in_array(strtolower($this->url->getScheme()), array('https', 'http'))
        ) {
            throw new HTTP_Request2_LogicException(
                'HTTP_Request2 needs an absolute HTTP(S) request URL, '
                . ($this->url instanceof Net_URL2
                   ? "'" . $this->url->__toString() . "'" : 'none')
                . ' given',
                HTTP_Request2_Exception::INVALID_ARGUMENT
            );
        }
        if (empty($this->adapter)) {
            $this->setAdapter($this->getConfig('adapter'));
        }
        // magic_quotes_runtime may break file uploads and chunked response
        // processing; see bug #4543. Don't use ini_get() here; see bug #16440.
        if ($magicQuotes = get_magic_quotes_runtime()) {
            set_magic_quotes_runtime(false);
        }
        // force using single byte encoding if mbstring extension overloads
        // strlen() and substr(); see bug #1781, bug #10605
        if (extension_loaded('mbstring') && (2 & ini_get('mbstring.func_overload'))) {
            $oldEncoding = mb_internal_encoding();
            mb_internal_encoding('8bit');
        }

        try {
            $response = $this->adapter->sendRequest($this);
        } catch (Exception $e) {
        }
        // cleanup in either case (poor man's "finally" clause)
        if ($magicQuotes) {
            set_magic_quotes_runtime(true);
        }
        if (!empty($oldEncoding)) {
            mb_internal_encoding($oldEncoding);
        }
        // rethrow the exception
        if (!empty($e)) {
            throw $e;
        }
        return $response;
    }

Sends the request and returns the response

@throws   HTTP_Request2_Exception
@return   HTTP_Request2_Response


protected static function detectMimeType($filename)
    {
        // finfo extension from PECL available
        if (function_exists('finfo_open')) {
            if (!isset(self::$_fileinfoDb)) {
                self::$_fileinfoDb = @finfo_open(FILEINFO_MIME);
            }
            if (self::$_fileinfoDb) {
                $info = finfo_file(self::$_fileinfoDb, $filename);
            }
        }
        // (deprecated) mime_content_type function available
        if (empty($info) && function_exists('mime_content_type')) {
            return mime_content_type($filename);
        }
        return empty($info)? 'application/octet-stream': $info;
    }

Tries to detect MIME type of a file

The method will try to use fileinfo extension if it is available,
deprecated mime_content_type() function in the other case. If neither
works, default 'application/octet-stream' MIME type is returned

@param string $filename file name

@return   string  file MIME type


public function showAction(Setting $setting)
    {
        $editForm = $this->createForm($this->get('amulen.dashboard.form.setting'), $setting, array(
            'action' => $this->generateUrl('admin_amulen_setting_update', array('id' => $setting->getid())),
            'method' => 'PUT',
        ));
        $deleteForm = $this->createDeleteForm($setting->getId(), 'admin_amulen_setting_delete');

        return array(

            'setting' => $setting, 'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),

        );
    }

public function showAction ( Setting $ setting ) { $ editForm = $ this -> createForm ( $ this -> get ( 'amulen.dashboard.form.setting' ) , $ setting , array ( 'action' => $ this -> generateUrl ( 'admin_amulen_setting_update' , array ( 'id' => $ setting -> getid ( ) ) ) , 'method' => 'PUT' , ) ) ; $ deleteForm = $ this -> createDeleteForm ( $ setting -> getId ( ) , 'admin_amulen_setting_delete' ) ; return array ( 'setting' => $ setting , 'edit_form' => $ editForm -> createView ( ) , 'delete_form' => $ deleteForm -> createView ( ) , ) ; }

Finds and displays a Setting entity.

@Route("/{id}/show", name="admin_amulen_setting_show", requirements={"id"="\d+"})
@Method("GET")
@Template()


public function newAction()
    {
        $setting = new Setting();
        $form = $this->createForm($this->get('amulen.dashboard.form.setting'), $setting);

        return array(
            'setting' => $setting,
            'form' => $form->createView(),
        );
    }

public function newAction ( ) { $ setting = new Setting ( ) ; $ form = $ this -> createForm ( $ this -> get ( 'amulen.dashboard.form.setting' ) , $ setting ) ; return array ( 'setting' => $ setting , 'form' => $ form -> createView ( ) , ) ; }

Displays a form to create a new Setting entity.

@Route("/new", name="admin_amulen_setting_new")
@Method("GET")
@Template()

Displays a form to create a new Setting entity .


public function createAction(Request $request)
    {
        $setting = new Setting();
        $form = $this->createForm($this->get('amulen.dashboard.form.setting'), $setting);
        if ($form->handleRequest($request)->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($setting);
            $em->flush();

            return $this->redirect($this->generateUrl('admin_amulen_setting_show', array('id' => $setting->getId())));
        }

        return array(
            'setting' => $setting,
            'form' => $form->createView(),
        );
    }

public function createAction ( Request $ request ) { $ setting = new Setting ( ) ; $ form = $ this -> createForm ( $ this -> get ( 'amulen.dashboard.form.setting' ) , $ setting ) ; if ( $ form -> handleRequest ( $ request ) -> isValid ( ) ) { $ em = $ this -> getDoctrine ( ) -> getManager ( ) ; $ em -> persist ( $ setting ) ; $ em -> flush ( ) ; return $ this -> redirect ( $ this -> generateUrl ( 'admin_amulen_setting_show' , array ( 'id' => $ setting -> getId ( ) ) ) ) ; } return array ( 'setting' => $ setting , 'form' => $ form -> createView ( ) , ) ; }

Creates a new Setting entity.

@Route("/create", name="admin_amulen_setting_create")
@Method("POST")
@Template("FlowcodeDashboardBundle:Setting:new.html.twig")


public function updateAction(Setting $setting, Request $request)
    {
        $editForm = $this->createForm($this->get('amulen.dashboard.form.setting'), $setting, array(
            'action' => $this->generateUrl('admin_amulen_setting_update', array('id' => $setting->getid())),
            'method' => 'PUT',
        ));
        if ($editForm->handleRequest($request)->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirect($this->generateUrl('admin_amulen_setting_show', array('id' => $setting->getId())));
        }
        $deleteForm = $this->createDeleteForm($setting->getId(), 'admin_amulen_setting_delete');

        return array(
            'setting' => $setting,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

public function updateAction ( Setting $ setting , Request $ request ) { $ editForm = $ this -> createForm ( $ this -> get ( 'amulen.dashboard.form.setting' ) , $ setting , array ( 'action' => $ this -> generateUrl ( 'admin_amulen_setting_update' , array ( 'id' => $ setting -> getid ( ) ) ) , 'method' => 'PUT' , ) ) ; if ( $ editForm -> handleRequest ( $ request ) -> isValid ( ) ) { $ this -> getDoctrine ( ) -> getManager ( ) -> flush ( ) ; return $ this -> redirect ( $ this -> generateUrl ( 'admin_amulen_setting_show' , array ( 'id' => $ setting -> getId ( ) ) ) ) ; } $ deleteForm = $ this -> createDeleteForm ( $ setting -> getId ( ) , 'admin_amulen_setting_delete' ) ; return array ( 'setting' => $ setting , 'edit_form' => $ editForm -> createView ( ) , 'delete_form' => $ deleteForm -> createView ( ) , ) ; }

Edits an existing Setting entity.

@Route("/{id}/update", name="admin_amulen_setting_update", requirements={"id"="\d+"})
@Method("PUT")
@Template("FlowcodeDashboardBundle:Setting:edit.html.twig")


public function where($expression, $value = null)
    {
        // shortcut : id
        if(is_int($expression) and !$value) {
            $expression = ['id' => $expression];
        }
        // force array
        elseif(!is_array($expression)) {
            $expression = [$expression => $value];
        }

        // parse each expression
        foreach($expression as $condition => $input) {

            // parse condition
            if(!preg_match('/^(?P<field>[a-zA-Z_0-9]+)( (?P<operator>.+))?$/', $condition, $extract)) {
                throw new \PDOException('Invalid expression "' . $condition . '"');
            }

            // clean condition
            $field = trim($extract['field']);
            $operator = isset($extract['operator'])
                ? strtolower(trim($extract['operator'], ' ?'))
                : null;

            // implicit '=' or 'in'
            if(!$operator) {
                $operator = is_array($input)
                    ? reset($this->complexOperators)
                    : reset($this->simpleOperators);
            }

            // simple operators
            if(in_array($operator, $this->simpleOperators)) {
                if(is_array($input)) {
                    throw new \PDOException('Operator "' . $operator . '" needs only one input value, in "' . $condition . '"');
                }

                $condition = '`' . $field . '` ' . $operator . ' ?';
            }
            // complex operators
            elseif(in_array($operator, $this->complexOperators)) {
                if(!is_array($input) or empty($input)) {
                    throw new \PDOException('Operator "' . $operator . '" needs multiple input values, in "' . $condition . '"');
                }

                $placeholders = array_fill(0, count($input), '?');
                $condition = '`' . $field . '` ' . $operator . ' (' . implode(', ', $placeholders) . ')';
            }
            // tuple operators
            elseif(in_array($operator, $this->tupleOperators)) {
                if(!is_array($input) or count($input) != 2) {
                    throw new \PDOException('Operator "' . $operator . '" needs exactly two input value, in "' . $condition . '"');
                }

                $condition = '`' . $field . '` ' . $operator . ' ? and ?';
            }
            // unknown operator
            else {
                throw new \PDOException('Invalid operator in "' . $condition . '"');
            }

            $this->where[$condition] = $input;
        }

        return $this;
    }

Filter by conditions

@param string $expression
@param mixed $value
@return $this


public function withStatus($code, $reason_phrase = '')
    {
        if (!in_array($code, array_keys($this->status_codes))) {
            throw new InvalidArgumentException(
                'HTTP Status Code is invalid'
            );
        }

        $response = clone $this;
        $response->status_code = (int)$code;
        $response->reason_phrase = (string)$reason_phrase ?? $this->status_code[$code];

        return $response;
    }

public
function
withStatus
(
$
code
,
$
reason_phrase
=
''
)
{
if
(
!
in_array
(
$
code
,
array_keys
(
$
this
->
status_codes
)
)
)
{
throw
new
InvalidArgumentException
(
'HTTP Status Code is invalid'
)
;
}
$
response
=
clone
$
this
;
$
response
->
status_code
=
(
int
)
$
code
;
$
response
->
reason_phrase
=
(
string
)
$
reason_phrase
??
$
this
->
status_code
[
$
code
]
;
return
$
response
;
}

Return an instance with the specified status code and, optionally, reason phrase.
If no reason phrase is specified, implementations MAY choose to default
to the RFC 7231 or IANA recommended reason phrase for the response's
status code.
This method MUST be implemented in such a way as to retain the
immutability of the message, and MUST return an instance that has the
updated status and reason phrase.

@link http://tools.ietf.org/html/rfc7231#section-6
@link http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
@param int $code The 3-digit integer result code to set.
@param string $reason_phrase The reason phrase to use with the
provided status code; if none is provided, implementations MAY
use the defaults as suggested in the HTTP specification.
@return ResponseInterface
@throws \InvalidArgumentException For invalid status code arguments.

Return an instance with the specified status code and optionally reason phrase . If no reason phrase is specified implementations MAY choose to default to the RFC 7231 or IANA recommended reason phrase for the response s status code . This method MUST be implemented in such a way as to retain the immutability of the message and MUST return an instance that has the updated status and reason phrase .


public function remove($params = array())
    {
        $this->adapter->execute($this->toSql(), array_merge($this->params(), $this->params(true), $params));

        return true;
    }

public function remove ( $ params = array ( ) ) { $ this -> adapter -> execute ( $ this -> toSql ( ) , array_merge ( $ this -> params ( ) , $ this -> params ( true ) , $ params ) ) ; return true ; }


public function hasEventListeners($event) {
        return !empty($this->listeners[$event]) || !empty($this->onceListeners[$event]);
    }

public function hasEventListeners ( $ event ) { return ! empty ( $ this -> listeners [ $ event ] ) || ! empty ( $ this -> onceListeners [ $ event ] ) ; }

Check attached event listeners for particular event
@param string $event
@return bool


protected function field($name, $default = null) {
        return array_key_exists($name, $this->data) ? $this->data[$name] : $default;
    }

protected function field ( $ name , $ default = null ) { return array_key_exists ( $ name , $ this -> data ) ? $ this -> data [ $ name ] : $ default ; }

Get the data for a field
@param string $name Field name
@param mixed $default Default value if not defined
@return mixed


protected function msg($msg, array $params = []) {
        return array_key_exists($msg, $this->messages) ? vsprintf($this->messages[$msg], $params) : null;
    }

protected function msg ( $ msg , array $ params = [ ] ) { return array_key_exists ( $ msg , $ this -> messages ) ? vsprintf ( $ this -> messages [ $ msg ] , $ params ) : null ; }

Use a predefined error message
@param string $msg Error message key
@param array $params Error message params
@return string


public function createAccessDeniedHttpException($message = 'Permission Denied!', \Exception $previous = null)
    {
        return new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException($message, $previous);
    }

public
function
createAccessDeniedHttpException
(
$
message
=
'Permission Denied!'
,
\
Exception
$
previous
=
)
{
return
new
\
Symfony
\
Component
\
HttpKernel
\
Exception
\
AccessDeniedHttpException
(
$
message
,
$
previous
)
;
}

Returns a AccessDeniedHttpException.

This will result in a 403 response code. Usage example:

throw $this->createAccessDeniedHttpException('Permission Denied!');

@param string    $message  A message
@param \Exception $previous The previous exception

@return \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException


protected function setFlash($type,$message,$parameters = array(),$domain = 'flashes')
    {
        return $this->get('session')->getBag('flashes')->add($type,$this->trans($message, $parameters, $domain));
    }

protected function setFlash ( $ type , $ message , $ parameters = array ( ) , $ domain = 'flashes' ) { return $ this -> get ( 'session' ) -> getBag ( 'flashes' ) -> add ( $ type , $ this -> trans ( $ message , $ parameters , $ domain ) ) ; }

Envia un mensaje flash

@param array $type success|error
@param type $message
@param type $parameters
@param type $domain
@return type


function commitTransaction(){
		$this->log("COMMIT SAVE_POINT_".$this->transactionCount);
		$this->transactionCount--;
		if($this->transactionCount == 0){
			parent::commit();
			$this->log("COMMIT REAL");
		}
		return $this->transactionCount;
	}

function
commitTransaction
(
)
{
$
this
->
log
(
"COMMIT SAVE_POINT_"
.
$
this
->
transactionCount
)
;
$
this
->
transactionCount
;
if
(
$
this
->
transactionCount
==
0
)
{
parent
::
commit
(
)
;
$
this
->
log
(
"COMMIT REAL"
)
;
}
return
$
this
->
transactionCount
;
}

commits the last transaction

@return integer , number of live transactions after executing this method


function formatDate($dateStr=null,$includeTime=null){
		if($dateStr === null){
			$date = time();
		}else if(is_string($dateStr)){
			$date = strtotime($dateStr);
		}else if(is_integer($dateStr)){
			$date = $dateStr;
		}else{
			throw new InvalidInputException('1st parameter should be either a string or integer or null');
		}
		$format = "Y-m-d";
		if(isset($includeTime)){
			$format .= " H:i:s";
		}
		$mysqlDate = date($format,$date);
		return $mysqlDate;
	}

this method formats date for this connection

@param string|integer $dateStr time in string or timestamp in integer
@param boolean $includeTime

@return string , formatted date as string


function formatTime($hh=0,$mm=0,$ss=0,$ampm="AM"){

		$ampm = strtoupper($ampm);

		$hhUpperBound = 12;
		if($ampm == "PM"){
			$hhUpperBound--;
		}

		if(!( (0 <= $hh && $hh <= $hhUpperBound) &&
			  (0 <= $mm && $mm <= 60) &&
			  (0 <= $ss && $ss <= 60)	)
				){
			throw new InvalidInputException('invalid parameters');
		}

		if($ampm == "PM"){
			if($hh != 12){
				$hh = $hh+12;
			}
		}else if($ampm == "AM"){
			if($hh == 12){
				$hh = 0;
			}
		}else{
			throw new InvalidInputException('last parameter should be either a AM or PM in string');
		}
		if($hh < 10){
			$hh = "0".$hh;
		}

		if($mm < 10){
			$mm = "0".$mm;
		}

		if($ss < 10){
			$ss = "0".$ss;
		}

		$mysqlTime = $hh.":".$mm.":".$ss;
		return $mysqlTime;
	}

this method formats time for this connection

@param number $hh
@param number $mm
@param number $ss
@param string $ampm

@return string represenation of time


function formatBoolean($value){
		if(is_string($value)){
			if(strtoupper($value) == "TRUE"){
				$value = '1';
			}else if(strtoupper($value) == "FALSE"){
				$value = '0';
			}else{
				throw new InvalidInputException("Not a boolean value");
			}
		}elseif ($value == true){
			$value = '1';
		}elseif ($value == false){
			$value = '0';
		}else{
			throw new InvalidInputException("Not a boolean value");
		}
		return $value;
	}

function
formatBoolean
(
$
value
)
{
if
(
is_string
(
$
value
)
)
{
if
(
strtoupper
(
$
value
)
==
"TRUE"
)
{
$
value
=
'1'
;
}
else
if
(
strtoupper
(
$
value
)
==
"FALSE"
)
{
$
value
=
'0'
;
}
else
{
throw
new
InvalidInputException
(
"Not a boolean value"
)
;
}
}
elseif
(
$
value
==
true
)
{
$
value
=
'1'
;
}
elseif
(
$
value
==
false
)
{
$
value
=
'0'
;
}
else
{
throw
new
InvalidInputException
(
"Not a boolean value"
)
;
}
return
$
value
;
}

this method formats boolean for this connection

@param boolean|string $value


function setTimeZone($timeZone){
		if($this->currentTimeZone == $timeZone){
			// $timeZone is set already
			return;
		}
		$this->currentTimeZone = $timeZone;

		//convert php timezone into mysql timezone format
    	$dtz = new \DateTimeZone($timeZone);
    	$timeInTimeZone = new \DateTime('now', $dtz);

    	$sign = "+";
    	$offset = $dtz->getOffset( $timeInTimeZone ) / 3600;
    	if($offset < 0){
    		$sign = "-";
    		$offset = -1 * $offset;
    	}
    	$hourPart = intval($offset);
    	$minutePart = $offset-$hourPart;
    	$minutePart = $minutePart * 60;

    	$timeZoneForMySql = $sign.$hourPart.":".$minutePart;

    	// set the timezone in mysql
    	$this->query("SET time_zone='$timeZoneForMySql'");
    }

this method sets the timezone for this connection
@param string $timeZone , time zone in php


public function get($className, array $parameters = [])
    {
        if ($this->injectSelf($className)) {
            return $this;
        }

        $parameterKey = $this->getParameterStoreKey($parameters);

        $className = $this->resolve($className);

        if (!isset($this->services[$className][$parameterKey])) {
            $this->services[$className][$parameterKey] = $this->create($className, $parameters);
        }

        return $this->services[$className][$parameterKey];
    }

public function get ( $ className , array $ parameters = [ ] ) { if ( $ this -> injectSelf ( $ className ) ) { return $ this ; } $ parameterKey = $ this -> getParameterStoreKey ( $ parameters ) ; $ className = $ this -> resolve ( $ className ) ; if ( ! isset ( $ this -> services [ $ className ] [ $ parameterKey ] ) ) { $ this -> services [ $ className ] [ $ parameterKey ] = $ this -> create ( $ className , $ parameters ) ; } return $ this -> services [ $ className ] [ $ parameterKey ] ; }

Fetch a service with supplied parameters.
This method will call create for a new service and store them for later use.

@param string $className
@param array $parameters
@return object
@throws RuntimeException

Fetch a service with supplied parameters . This method will call create for a new service and store them for later use .


public function has($className, array $parameters = [])
    {
        if ($this->injectSelf($className)) {
            return true;
        }

        $parameterKey = $this->getParameterStoreKey($parameters);

        $className = $this->resolve($className);

        return isset($this->services[$className][$parameterKey]);
    }

public function has ( $ className , array $ parameters = [ ] ) { if ( $ this -> injectSelf ( $ className ) ) { return true ; } $ parameterKey = $ this -> getParameterStoreKey ( $ parameters ) ; $ className = $ this -> resolve ( $ className ) ; return isset ( $ this -> services [ $ className ] [ $ parameterKey ] ) ; }

Check if there is an instance in the container

@param string $className
@param array $parameters
@return bool


public function create($className, array $parameters = [])
    {
        if ($this->injectSelf($className)) {
            return $this;
        }

        $className = $this->resolve($className);

        $classMeta = $this->reflectionService->getClassMetaReflection($className);

        if ($classMeta->isInterface()) {
            throw new RuntimeException('Tried to create an interface ( ' . $className . ' ) without registered implementation.');
        }

        $object = $this->createObject($className, $parameters, $classMeta);

        return $object;
    }

public
function
create
(
$
className
,
array
$
parameters
=
[
]
)
{
if
(
$
this
->
injectSelf
(
$
className
)
)
{
return
$
this
;
}
$
className
=
$
this
->
resolve
(
$
className
)
;
$
classMeta
=
$
this
->
reflectionService
->
getClassMetaReflection
(
$
className
)
;
if
(
$
classMeta
->
isInterface
(
)
)
{
throw
new
RuntimeException
(
'Tried to create an interface ( '
.
$
className
.
' ) without registered implementation.'
)
;
}
$
object
=
$
this
->
createObject
(
$
className
,
$
parameters
,
$
classMeta
)
;
return
$
object
;
}

Create a class with supplied parameters.

Before a class is created the container will first check for a suitable resolver.

If an invalid class name was given, e.g. an interface without registered resolver,
throw a RuntimeException.

@param string $className
@param array $parameters
@return object
@throws RuntimeException

Create a class with supplied parameters .


public function addResolver(ResolverInterface $resolver, $priority = 0)
    {
        if (!isset($this->prioritizedResolvers[$priority])) {
            $this->prioritizedResolvers[$priority] = [];
        }

        array_push($this->prioritizedResolvers[$priority], $resolver);
        krsort($this->prioritizedResolvers);
    }

public function addResolver ( ResolverInterface $ resolver , $ priority = 0 ) { if ( ! isset ( $ this -> prioritizedResolvers [ $ priority ] ) ) { $ this -> prioritizedResolvers [ $ priority ] = [ ] ; } array_push ( $ this -> prioritizedResolvers [ $ priority ] , $ resolver ) ; krsort ( $ this -> prioritizedResolvers ) ; }

Add a resolver

@param ResolverInterface $resolver
@param int $priority                 Higher priority means it will be used before one
with a lower priority.


public function add($object)
    {
        $className = '\\' . get_class($object);

        if ($this->injectSelf($className)) {
            throw new InvalidArgumentException('Tried to add a container instance');
        }

        $parameterKey = $this->getParameterStoreKey([]);

        if (isset($this->services[$className][$parameterKey])) {
            throw new InvalidArgumentException('Tried to add a service instance which already exists');
        }

        $this->services[$className][$parameterKey] = $object;
    }

Add an already created service to the container.

@param $object
@throws InvalidArgumentException

Add an already created service to the container .


public function getPool()
    {
        if (!isset($this->_pool)) {
            $poolConfig = [
                'loop' => $this->loop,
                'clientConfig' => [
                    ['class' => pgConnection::class],
                    [
                        $this->connectionParams,
                        $this->loop,
                        $this->connector
                    ]
                ]
            ];
            $poolConfig = ArrayHelper::merge($this->poolConfigDefault, $this->poolConfig, $poolConfig);
            $this->_pool = new Pool($poolConfig);
        }
        return $this->_pool;
    }

public function getPool ( ) { if ( ! isset ( $ this -> _pool ) ) { $ poolConfig = [ 'loop' => $ this -> loop , 'clientConfig' => [ [ 'class' => pgConnection :: class ] , [ $ this -> connectionParams , $ this -> loop , $ this -> connector ] ] ] ; $ poolConfig = ArrayHelper :: merge ( $ this -> poolConfigDefault , $ this -> poolConfig , $ poolConfig ) ; $ this -> _pool = new Pool ( $ poolConfig ) ; } return $ this -> _pool ; }

Get pool of connections
@return Pool|null


public function query($s)
    {
        return Observable::defer(function() use ($s) {
            $conn = $this->getLeastBusyConnection();

            return $conn->query($s);
        });
    }

public function query ( $ s ) { return Observable :: defer ( function ( ) use ( $ s ) { $ conn = $ this -> getLeastBusyConnection ( ) ; return $ conn -> query ( $ s ) ; } ) ; }

Execute simple statement without parameters
@param string $s
@return Observable


public function executeStatement(string $queryString, array $parameters = [])
    {
        return Observable::defer(function() use ($queryString, $parameters) {
            $conn = $this->getLeastBusyConnection();

            return $conn->executeStatement($queryString, $parameters);
        });
    }

public function executeStatement ( string $ queryString , array $ parameters = [ ] ) { return Observable :: defer ( function ( ) use ( $ queryString , $ parameters ) { $ conn = $ this -> getLeastBusyConnection ( ) ; return $ conn -> executeStatement ( $ queryString , $ parameters ) ; } ) ; }

Execute statement with parameters
@param string $queryString
@param array  $parameters
@return Observable


private function createNewConnection($addToPool = true, $params = [])
    {
        // no idle connections were found - spin up new one
        $params = ArrayHelper::merge($this->connectionParams, $params);
        $connection = new pgConnection($params, $this->loop, $this->connector);
        if (!$addToPool || $this->autoDisconnect) {
            return $connection;
        }

        $this->connections[] = $connection;

        $connection->on('close', function() use ($connection) {
            $this->connections = array_filter($this->connections, function($c) use ($connection) {
                return $connection !== $c;
            });
            $this->connections = array_values($this->connections);
        });

        return $connection;
    }

Create new connection
@param bool  $addToPool
@param array $params
@return pgConnection
@deprecated Since Pool is used
@see getPool()


private function getLeastBusyConnectionOld() : pgConnection
    {
        if (count($this->connections) === 0) {
            // try to spin up another connection to return
            $conn = $this->createNewConnection();
            if ($conn === null) {
                throw new Exception('There are no connections. Cannot find least busy one and could not create a new one.');
            }

            return $conn;
        }

        $min = reset($this->connections);

        foreach ($this->connections as $connection) {
            // if this connection is idle - just return it
            if ($connection->getBacklogLength() === 0 && $connection->getState() === pgConnection::STATE_READY) {
                return $connection;
            }

            if ($min->getBacklogLength() > $connection->getBacklogLength()) {
                $min = $connection;
            }
        }

        if (count($this->connections) < $this->maxConnections) {
            return $this->createNewConnection();
        }

        return $min;
    }

Get least busy connection, with idle state or at least with minimum queued queries count
@return pgConnection
@throws Exception
@deprecated
@see getLeastBusyConnection()

Get least busy connection with idle state or at least with minimum queued queries count


public static function assetsInstall(Event $event)
    {
        $options = self::getOptions($event);
        $consoleDir = self::getConsoleDir($event, 'install assets');

        if (null === $consoleDir) {
            return;
        }

        $webDir = $options['web-dir'];

        $symlink = '';
        if ($options['assets-install'] == 'symlink') {
            $symlink = '--symlink ';
        } elseif ($options['assets-install'] == 'relative') {
            $symlink = '--symlink --relative ';
        }

        if (!self::hasDirectory(
            $event, 'web-dir', $webDir, 'install assets'
        )) {
            return;
        }

        static::executeCommand(
            $event, $consoleDir, 'assets:install '.
            $symlink.escapeshellarg($webDir)
        );
    }

public
static
function
assetsInstall
(
Event
$
event
)
{
$
options
=
self
::
getOptions
(
$
event
)
;
$
consoleDir
=
self
::
getConsoleDir
(
$
event
,
'install assets'
)
;
if
(
===
$
consoleDir
)
{
return
;
}
$
webDir
=
$
options
[
'web-dir'
]
;
$
symlink
=
''
;
if
(
$
options
[
'assets-install'
]
==
'symlink'
)
{
$
symlink
=
'--symlink '
;
}
elseif
(
$
options
[
'assets-install'
]
==
'relative'
)
{
$
symlink
=
'--symlink --relative '
;
}
if
(
!
self
::
hasDirectory
(
$
event
,
'web-dir'
,
$
webDir
,
'install assets'
)
)
{
return
;
}
static
::
executeCommand
(
$
event
,
$
consoleDir
,
'assets:install '
.
$
symlink
.
escapeshellarg
(
$
webDir
)
)
;
}

Installs the assets under the web root directory.

For better interoperability, assets are copied
instead of symlinked by default.

Even if symlinks work on Windows, this is only true on Windows
Vista and later, but then, only when running the console with admin
rights or when disabling the strict user permission checks
(which can be done on Windows 7 but not on Windows Vista).

@param Event $event Composer event instance

@return void

Installs the assets under the web root directory .


public function getReflectionClass($className)
    {
        if (isset($this->classReflections[$className])) {
            return $this->classReflections[$className];
        }

        $class = new \ReflectionClass($className);
        $this->classReflections[$className] = $class;

        return $class;
    }

public function getReflectionClass ( $ className ) { if ( isset ( $ this -> classReflections [ $ className ] ) ) { return $ this -> classReflections [ $ className ] ; } $ class = new \ ReflectionClass ( $ className ) ; $ this -> classReflections [ $ className ] = $ class ; return $ class ; }

Get the reflection class instance for a class name.

@param string $className Full class name.

@return \ReflectionClass

Get the reflection class instance for a class name .


public function getClassVersion($className)
    {
        if (isset($this->classVersions[$className])) {
            return $this->classVersions[$className];
        }

        $class = $this->getReflectionClass($className);

        $versionAnnotation = $this->reader->getClassAnnotation(
            $class,
            'Evispa\ObjectMigration\Annotations\Version'
        );

        if (null === $versionAnnotation) {
            throw new Exception\NotVersionedException($className);
        }

        $version = $versionAnnotation->version;

        $this->classVersions[$className] = $version;

        return $version;
    }

Get class version annotation for a class name.

@param string $className Full class name.

@return string

@throws Exception\NotVersionedException If object is not versioned.

Get class version annotation for a class name .


private function findClassNameByVersion($startFromClassName, $version, &$visited = array())
    {
        $versionAnnotation = $this->reader->getClassAnnotation(
            new \ReflectionClass($startFromClassName),
            'Evispa\ObjectMigration\Annotations\Version'
        );

        if ($versionAnnotation->version === $version) {
            return $startFromClassName;
        }

        $migrationAnnotations = $this->getClassMigrationMethodInfo($startFromClassName);
        /** @var MethodInfo $methodInfo */
        foreach ($migrationAnnotations as $methodInfo) {
            if ($methodInfo->annotation->from && !in_array($methodInfo->annotation->from, $visited)) {
                $visited[] = $methodInfo->annotation->from;
                $className = $this->getClassNameByVersion($methodInfo->annotation->from, $version, $visited);
                if ($className) {
                    return $className;
                }
            }

            if ($methodInfo->annotation->to && !in_array($methodInfo->annotation->to, $visited)) {
                $visited[] = $methodInfo->annotation->to;
                $className = $this->getClassNameByVersion($methodInfo->annotation->to, $version, $visited);
                if ($className) {
                    return $className;
                }
            }
        }

        return null;
    }

Search for class name by version id

@param string $startFromClassName
@param string $version
@param array  $visited

@return null|string


public function getClassMigrationMethods($className)
    {
        if (isset($this->classMigrationMethods[$className])) {
            return $this->classMigrationMethods[$className];
        }

        $migrationAnnotations = $this->getClassMigrationMethodInfo($className);

        $migrationMethods = new MigrationMethods();

        foreach ($migrationAnnotations as $migrationAnnotation) {
            $method = $migrationAnnotation->method;
            $migrationAnnotation = $migrationAnnotation->annotation;

            if (null !== $migrationAnnotation->from) {
                if (false === $method->isStatic() || 2 !== $method->getNumberOfParameters()) {
                    throw new \LogicException(
                        'Method "' . $method->getName(
                        ) . '" in "' . $className . '" should be static and require 2 parameters.'
                    );
                }

                if ($migrationAnnotation->from === $className) {
                    throw new \LogicException(
                        'Method "' . $method->getName(
                        ) . '" in "' . $className . '" should have a migration from a different class.'
                    );
                }

                $otherClass = $migrationAnnotation->from;
                $otherClassVersion = $this->getClassVersion($otherClass);
                $migrationMethods->from[$otherClassVersion] = new CreateAction($method);

            } elseif (null !== $migrationAnnotation->to) {
                if (true === $method->isStatic() || 1 !== $method->getNumberOfParameters()) {
                    throw new \LogicException(
                        'Method "' . $method->getName(
                        ) . '" in "' . $className . '" should not be static and require 1 parameter.'
                    );
                }

                if ($migrationAnnotation->to === $className) {
                    throw new \LogicException(
                        'Method "' . $method->getName(
                        ) . '" in "' . $className . '" should have a migration to a different class.'
                    );
                }

                $otherClass = $migrationAnnotation->to;
                $otherClassVersion = $this->getClassVersion($otherClass);
                $migrationMethods->to[$otherClassVersion] = new CloneAction($method);

            }
        }

        $this->classMigrationMethods[$className] = $migrationMethods;

        return $migrationMethods;
    }

Get migrations for a class.

@param string $className

@return MigrationMethods

@throws \LogicException


public function getRequiredClassOptions($className)
    {
        $requiredOptions = array();

        $scanList = array($className => true);

        $scannedSourceNames = array();

        while (true) {
            if (0 === count($scanList)) {
                break;
            }

            // find new class names
            foreach ($scanList as $scanName => $_) {
                $annotations = $this->getClassMigrationMethodInfo($scanName);
                foreach ($annotations as $annotationInfo) {
                    if (null !== $annotationInfo->annotation->from) {
                        $newClass = $annotationInfo->annotation->from;
                        foreach ($annotationInfo->annotation->require as $requiredOption) {
                            $requiredOptions[$requiredOption] = array('from' => $newClass, 'to' => $scanName);
                        }
                    } elseif (null !== $annotationInfo->annotation->to) {
                        $newClass = $annotationInfo->annotation->to;
                        foreach ($annotationInfo->annotation->require as $requiredOption) {
                            $requiredOptions[$requiredOption] = array('from' => $scanName, 'to' => $newClass);
                        }
                    }

                    if (!isset($scannedSourceNames[$newClass])) {
                        $scanList[$newClass] = true;
                    }
                }

                unset($scanList[$scanName]);

                if (!isset($scannedSourceNames[$scanName])) {
                    $scannedSourceNames[$scanName] = true;
                }
            }
        }

        return $requiredOptions;
    }

public
function
getRequiredClassOptions
(
$
className
)
{
$
requiredOptions
=
array
(
)
;
$
scanList
=
array
(
$
className
=>
true
)
;
$
scannedSourceNames
=
array
(
)
;
while
(
true
)
{
if
(
0
===
count
(
$
scanList
)
)
{
break
;
}
// find new class names
foreach
(
$
scanList
as
$
scanName
=>
$
_
)
{
$
annotations
=
$
this
->
getClassMigrationMethodInfo
(
$
scanName
)
;
foreach
(
$
annotations
as
$
annotationInfo
)
{
if
(
!==
$
annotationInfo
->
annotation
->
from
)
{
$
newClass
=
$
annotationInfo
->
annotation
->
from
;
foreach
(
$
annotationInfo
->
annotation
->
require
as
$
requiredOption
)
{
$
requiredOptions
[
$
requiredOption
]
=
array
(
'from'
=>
$
newClass
,
'to'
=>
$
scanName
)
;
}
}
elseif
(
!==
$
annotationInfo
->
annotation
->
to
)
{
$
newClass
=
$
annotationInfo
->
annotation
->
to
;
foreach
(
$
annotationInfo
->
annotation
->
require
as
$
requiredOption
)
{
$
requiredOptions
[
$
requiredOption
]
=
array
(
'from'
=>
$
scanName
,
'to'
=>
$
newClass
)
;
}
}
if
(
!
isset
(
$
scannedSourceNames
[
$
newClass
]
)
)
{
$
scanList
[
$
newClass
]
=
true
;
}
}
unset
(
$
scanList
[
$
scanName
]
)
;
if
(
!
isset
(
$
scannedSourceNames
[
$
scanName
]
)
)
{
$
scannedSourceNames
[
$
scanName
]
=
true
;
}
}
}
return
$
requiredOptions
;
}

Find all the options required for all the migrations for this class.

@param string $className Class name.

@return array

Find all the options required for all the migrations for this class .


public function showAction(Job $job)
    {
        $editForm = $this->createForm(new JobType(), $job, array(
            'action' => $this->generateUrl('admin_amulen_job_update', array('id' => $job->getid())),
            'method' => 'PUT',
        ));
        $deleteForm = $this->createDeleteForm($job->getId(), 'admin_amulen_job_delete');

        return array(

            'job' => $job, 'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),

        );
    }

public function showAction ( Job $ job ) { $ editForm = $ this -> createForm ( new JobType ( ) , $ job , array ( 'action' => $ this -> generateUrl ( 'admin_amulen_job_update' , array ( 'id' => $ job -> getid ( ) ) ) , 'method' => 'PUT' , ) ) ; $ deleteForm = $ this -> createDeleteForm ( $ job -> getId ( ) , 'admin_amulen_job_delete' ) ; return array ( 'job' => $ job , 'edit_form' => $ editForm -> createView ( ) , 'delete_form' => $ deleteForm -> createView ( ) , ) ; }

Finds and displays a Job entity.

@Route("/{id}/show", name="admin_amulen_job_show", requirements={"id"="\d+"})
@Method("GET")
@Template()


public function newAction()
    {
        $job = new Job();
        $form = $this->createForm(new JobType(), $job);

        return array(
            'job' => $job,
            'form' => $form->createView(),
        );
    }

public function newAction ( ) { $ job = new Job ( ) ; $ form = $ this -> createForm ( new JobType ( ) , $ job ) ; return array ( 'job' => $ job , 'form' => $ form -> createView ( ) , ) ; }

Displays a form to create a new Job entity.

@Route("/new", name="admin_amulen_job_new")
@Method("GET")
@Template()

Displays a form to create a new Job entity .


public function createAction(Request $request)
    {
        $job = new Job();
        $form = $this->createForm(new JobType(), $job);
        if ($form->handleRequest($request)->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($job);
            $em->flush();

            return $this->redirect($this->generateUrl('admin_amulen_job_show', array('id' => $job->getId())));
        }

        return array(
            'job' => $job,
            'form' => $form->createView(),
        );
    }

public function createAction ( Request $ request ) { $ job = new Job ( ) ; $ form = $ this -> createForm ( new JobType ( ) , $ job ) ; if ( $ form -> handleRequest ( $ request ) -> isValid ( ) ) { $ em = $ this -> getDoctrine ( ) -> getManager ( ) ; $ em -> persist ( $ job ) ; $ em -> flush ( ) ; return $ this -> redirect ( $ this -> generateUrl ( 'admin_amulen_job_show' , array ( 'id' => $ job -> getId ( ) ) ) ) ; } return array ( 'job' => $ job , 'form' => $ form -> createView ( ) , ) ; }

Creates a new Job entity.

@Route("/create", name="admin_amulen_job_create")
@Method("POST")
@Template("FlowcodeDashboardBundle:Job:new.html.twig")


public function updateAction(Job $job, Request $request)
    {
        $editForm = $this->createForm(new JobType(), $job, array(
            'action' => $this->generateUrl('admin_amulen_job_update', array('id' => $job->getid())),
            'method' => 'PUT',
        ));
        if ($editForm->handleRequest($request)->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirect($this->generateUrl('admin_amulen_job_show', array('id' => $job->getId())));
        }
        $deleteForm = $this->createDeleteForm($job->getId(), 'admin_amulen_job_delete');

        return array(
            'job' => $job,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

public function updateAction ( Job $ job , Request $ request ) { $ editForm = $ this -> createForm ( new JobType ( ) , $ job , array ( 'action' => $ this -> generateUrl ( 'admin_amulen_job_update' , array ( 'id' => $ job -> getid ( ) ) ) , 'method' => 'PUT' , ) ) ; if ( $ editForm -> handleRequest ( $ request ) -> isValid ( ) ) { $ this -> getDoctrine ( ) -> getManager ( ) -> flush ( ) ; return $ this -> redirect ( $ this -> generateUrl ( 'admin_amulen_job_show' , array ( 'id' => $ job -> getId ( ) ) ) ) ; } $ deleteForm = $ this -> createDeleteForm ( $ job -> getId ( ) , 'admin_amulen_job_delete' ) ; return array ( 'job' => $ job , 'edit_form' => $ editForm -> createView ( ) , 'delete_form' => $ deleteForm -> createView ( ) , ) ; }

Edits an existing Job entity.

@Route("/{id}/update", name="admin_amulen_job_update", requirements={"id"="\d+"})
@Method("PUT")
@Template("FlowcodeDashboardBundle:Job:edit.html.twig")


public function setClientFilename($file_name)
    {
        if (is_string($file_name)) {
            $this->client_file_name = $file_name;
            $_ext = $this->guessExtension();
            if (!empty($_ext) && !strstr($file_name, $_ext))
                $this->client_file_name .= '.'.$_ext;
        } else {
            throw new InvalidArgumentException(
                sprintf('Client name of a file must be a string (got "%s")!', gettype($file_name))
            );
        }
    }

Set the client filename

@param   string  $file_name  The client filename for the file
@return  void
@throws   \CarteBlanche\Exception\InvalidArgumentException if the file name is not a string


public function guessExtension()
    {
        $_ext = $this->getExtension();
        if (empty($_ext) && $this->getRealPath()) {
            $finfo = new \finfo();
            $mime = $finfo->file( $this->getRealPath(), FILEINFO_MIME_TYPE );
            $_ext = str_replace('image/', '', $mime);
        }
        return $_ext;
    }

public function guessExtension ( ) { $ _ext = $ this -> getExtension ( ) ; if ( empty ( $ _ext ) && $ this -> getRealPath ( ) ) { $ finfo = new \ finfo ( ) ; $ mime = $ finfo -> file ( $ this -> getRealPath ( ) , FILEINFO_MIME_TYPE ) ; $ _ext = str_replace ( 'image/' , '' , $ mime ) ; } return $ _ext ; }

Get the file extension or guess it from MIME type if so ...

@return  string  The guessed extension
@see     \SplFileInfo::getExtension()


public function getMime()
    {
        if ($this->getRealPath()) {
            $finfo = new \finfo();
            return $finfo->file( $this->getRealPath(), FILEINFO_MIME_TYPE );
        }
        return null;
    }

public function getMime ( ) { if ( $ this -> getRealPath ( ) ) { $ finfo = new \ finfo ( ) ; return $ finfo -> file ( $ this -> getRealPath ( ) , FILEINFO_MIME_TYPE ) ; } return null ; }

Get the file miem string if possible

@return  string  The mime type info


public function getHumanSize( $decimals=2 )
    {
        $sz = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        $factor = floor((strlen($this->getSize()) - 1) / 3);
        if ($factor >= count($sz)) $factor = count($sz)-1;
        return sprintf("%.{$decimals}f", $this->getSize() / pow(1024, $factor)) . $sz[$factor];
    }

public function getHumanSize ( $ decimals = 2 ) { $ sz = array ( 'B' , 'KB' , 'MB' , 'GB' , 'TB' , 'PB' ) ; $ factor = floor ( ( strlen ( $ this -> getSize ( ) ) - 1 ) / 3 ) ; if ( $ factor >= count ( $ sz ) ) $ factor = count ( $ sz ) - 1 ; return sprintf ( "%.{$decimals}f" , $ this -> getSize ( ) / pow ( 1024 , $ factor ) ) . $ sz [ $ factor ] ; }

Get the file size in human readable string

@param   int     $decimals   The decimals number to use in calculated file size
@return  string  A human readable string describing a file size


public function getATimeAsDatetime()
    {
        $_date = $this->getATime();
        if (!empty($_date))
            return \DateTime::createFromFormat( 'U', $_date );
        return null;
    }

public function getATimeAsDatetime ( ) { $ _date = $ this -> getATime ( ) ; if ( ! empty ( $ _date ) ) return \ DateTime :: createFromFormat ( 'U' , $ _date ) ; return null ; }

Get the last access time on the file and return it as a DateTime object

@return  null|object     The datetime object if so


public function getCTimeAsDatetime()
    {
        $_date = $this->getCTime();
        if (!empty($_date))
            return \DateTime::createFromFormat( 'U', $_date );
        return null;
    }

public function getCTimeAsDatetime ( ) { $ _date = $ this -> getCTime ( ) ; if ( ! empty ( $ _date ) ) return \ DateTime :: createFromFormat ( 'U' , $ _date ) ; return null ; }

Get the creation time on the file and return it as a DateTime object

@return  null|object     The datetime object if so


public function getMTimeAsDatetime()
    {
        $_date = $this->getMTime();
        if (!empty($_date))
            return \DateTime::createFromFormat( 'U', $_date );
        return null;
    }

public function getMTimeAsDatetime ( ) { $ _date = $ this -> getMTime ( ) ; if ( ! empty ( $ _date ) ) return \ DateTime :: createFromFormat ( 'U' , $ _date ) ; return null ; }

Get the last modification time on the file and return it as a DateTime object

@return  null|object     The datetime object if so


public static function createFromContent( $file_content, $filename=null, $client_file_name=null )
    {
        $finfo = new \finfo();
        $mime = $finfo->buffer( $file_content, FILEINFO_MIME_TYPE );
        $extension = end(explode('/', $mime));
        if (is_null($filename)) {
            $_tmp_filename = md5( $file_content ).'.'.$extension;
            $filename = CarteBlanche::getFullPath('web_tmp_dir').$_tmp_filename;
            if (file_exists($filename)) {
                return new File( $filename, $client_file_name );
            }
        } elseif (end(explode('.', $filename))!=$extension) {
            $filename .= '.'.$extension;
        }

        $_tf = fopen($filename, 'a+');
        if ($_tf) {
            fwrite($_tf, $file_content);
            fclose($_tf);
            return new File( $filename, $client_file_name );
        }
        return null;
    }

public static function createFromContent ( $ file_content , $ filename = null , $ client_file_name = null ) { $ finfo = new \ finfo ( ) ; $ mime = $ finfo -> buffer ( $ file_content , FILEINFO_MIME_TYPE ) ; $ extension = end ( explode ( '/' , $ mime ) ) ; if ( is_null ( $ filename ) ) { $ _tmp_filename = md5 ( $ file_content ) . '.' . $ extension ; $ filename = CarteBlanche :: getFullPath ( 'web_tmp_dir' ) . $ _tmp_filename ; if ( file_exists ( $ filename ) ) { return new File ( $ filename , $ client_file_name ) ; } } elseif ( end ( explode ( '.' , $ filename ) ) != $ extension ) { $ filename .= '.' . $ extension ; } $ _tf = fopen ( $ filename , 'a+' ) ; if ( $ _tf ) { fwrite ( $ _tf , $ file_content ) ; fclose ( $ _tf ) ; return new File ( $ filename , $ client_file_name ) ; } return null ; }

Create a file with a content string and returns the created filename

@param   string  $file_content   The source file content
@param   string  $filename       The target filename (optional - automatic if not set)
@return  \CarteBlanche\Library\File


public function findAll()
    {
        $applications = array();

        foreach ($this->getRows() as $row) {
            $application = $this->createNew();
            $application->setId($row['id']);
            $application->setName($row['name']);
            $application->setUrl($row['url']);

            $applications[] = $application;
        }

        return $applications;
    }

public function findAll ( ) { $ applications = array ( ) ; foreach ( $ this -> getRows ( ) as $ row ) { $ application = $ this -> createNew ( ) ; $ application -> setId ( $ row [ 'id' ] ) ; $ application -> setName ( $ row [ 'name' ] ) ; $ application -> setUrl ( $ row [ 'url' ] ) ; $ applications [ ] = $ application ; } return $ applications ; }

Retrieve all applications

@return array


public function find($id)
    {
        foreach ($this->findAll() as $application) {
            if ($id == $application->getId()) {
                return $application;
            }
        }

        return null;
    }

public function find ( $ id ) { foreach ( $ this -> findAll ( ) as $ application ) { if ( $ id == $ application -> getId ( ) ) { return $ application ; } } return null ; }

Find application by ID

@param $id App ID
@return Application|null


public function create(Application $application)
    {
        $rows = $this->getRows();
        $id = sizeof($rows) + 1;

        $rows[] = array(
            'id' => $id,
            'name' => $application->getName(),
            'url' => $application->getUrl()
        );

        file_put_contents($this->filename, Yaml::dump($rows));
    }

public function create ( Application $ application ) { $ rows = $ this -> getRows ( ) ; $ id = sizeof ( $ rows ) + 1 ; $ rows [ ] = array ( 'id' => $ id , 'name' => $ application -> getName ( ) , 'url' => $ application -> getUrl ( ) ) ; file_put_contents ( $ this -> filename , Yaml :: dump ( $ rows ) ) ; }

Create an application

@param Application $application
@return mixed


public function delete(Application $application)
    {
        $rows = array();

        foreach ($this->getRows() as $row) {
            if ($row['id'] == $application->getId()) {
                continue;
            }
            $rows[] = $row;
        }

        file_put_contents($this->filename, Yaml::dump($rows));
    }

public function delete ( Application $ application ) { $ rows = array ( ) ; foreach ( $ this -> getRows ( ) as $ row ) { if ( $ row [ 'id' ] == $ application -> getId ( ) ) { continue ; } $ rows [ ] = $ row ; } file_put_contents ( $ this -> filename , Yaml :: dump ( $ rows ) ) ; }

Delete an application

@param Application $application
@return mixed


public function update(Application $application)
    {
        $rows = array();

        foreach ($this->getRows() as $row) {
            if ($row['id'] == $application->getId()) {
                $row = array(
                    'id'   => $application->getId(),
                    'name' => $application->getName(),
                    'url'  => $application->getUrl()
                );
            }
            $rows[] = $row;
        }

        file_put_contents($this->filename, Yaml::dump($rows));
    }

public function update ( Application $ application ) { $ rows = array ( ) ; foreach ( $ this -> getRows ( ) as $ row ) { if ( $ row [ 'id' ] == $ application -> getId ( ) ) { $ row = array ( 'id' => $ application -> getId ( ) , 'name' => $ application -> getName ( ) , 'url' => $ application -> getUrl ( ) ) ; } $ rows [ ] = $ row ; } file_put_contents ( $ this -> filename , Yaml :: dump ( $ rows ) ) ; }

Update an application

@param Application $application
@return mixex


private function getClosestDateIntervalBefore(\DateTime $date): DateTimeInterval
    {
        $tmpDate = clone $date;
        $dayOfWeek = (int)$tmpDate->format('N');
        $time = TimeBuilder::fromDate($tmpDate);

        if (null !== $day = $this->getDay($dayOfWeek)) {
            if (null !== $closestTime = $day->getClosestPreviousOpeningHoursInterval($time)) {
                return $this->buildDateTimeInterval($tmpDate, $closestTime);
            }
        }

        $tmpDate = $this->getDateBefore($tmpDate);

        $closestDay = $this->getClosestDayBefore((int)$tmpDate->format('N'));

        $closingTime = $closestDay->getClosingTime();
        $closestTime = $closestDay->getClosestPreviousOpeningHoursInterval($closingTime);

        return $this->buildDateTimeInterval($tmpDate, $closestTime);
    }

private function getClosestDateIntervalBefore ( \ DateTime $ date ) : DateTimeInterval { $ tmpDate = clone $ date ; $ dayOfWeek = ( int ) $ tmpDate -> format ( 'N' ) ; $ time = TimeBuilder :: fromDate ( $ tmpDate ) ; if ( null !== $ day = $ this -> getDay ( $ dayOfWeek ) ) { if ( null !== $ closestTime = $ day -> getClosestPreviousOpeningHoursInterval ( $ time ) ) { return $ this -> buildDateTimeInterval ( $ tmpDate , $ closestTime ) ; } } $ tmpDate = $ this -> getDateBefore ( $ tmpDate ) ; $ closestDay = $ this -> getClosestDayBefore ( ( int ) $ tmpDate -> format ( 'N' ) ) ; $ closingTime = $ closestDay -> getClosingTime ( ) ; $ closestTime = $ closestDay -> getClosestPreviousOpeningHoursInterval ( $ closingTime ) ; return $ this -> buildDateTimeInterval ( $ tmpDate , $ closestTime ) ; }

Get the closest business hours date interval before the given date.

@param \DateTime $date The given date.
@return DateTimeInterval

Get the closest business hours date interval before the given date .


private function getClosestDateIntervalAfter(\DateTime $date): DateTimeInterval
    {
        $tmpDate = clone $date;
        $dayOfWeek = (int)$tmpDate->format('N');
        $time = TimeBuilder::fromDate($tmpDate);

        if (null !== $day = $this->getDay($dayOfWeek)) {
            if (null !== $closestTime = $day->getClosestNextOpeningHoursInterval($time)) {
                return $this->buildDateTimeInterval($tmpDate, $closestTime);
            }
        }

        $tmpDate = $this->getDateAfter($tmpDate);

        $closestDay = $this->getClosestDayBefore((int)$tmpDate->format('N'));

        $openingTime = $closestDay->getOpeningTime();
        $closestTime = $closestDay->getClosestNextOpeningHoursInterval($openingTime);

        return $this->buildDateTimeInterval($tmpDate, $closestTime);
    }

private function getClosestDateIntervalAfter ( \ DateTime $ date ) : DateTimeInterval { $ tmpDate = clone $ date ; $ dayOfWeek = ( int ) $ tmpDate -> format ( 'N' ) ; $ time = TimeBuilder :: fromDate ( $ tmpDate ) ; if ( null !== $ day = $ this -> getDay ( $ dayOfWeek ) ) { if ( null !== $ closestTime = $ day -> getClosestNextOpeningHoursInterval ( $ time ) ) { return $ this -> buildDateTimeInterval ( $ tmpDate , $ closestTime ) ; } } $ tmpDate = $ this -> getDateAfter ( $ tmpDate ) ; $ closestDay = $ this -> getClosestDayBefore ( ( int ) $ tmpDate -> format ( 'N' ) ) ; $ openingTime = $ closestDay -> getOpeningTime ( ) ; $ closestTime = $ closestDay -> getClosestNextOpeningHoursInterval ( $ openingTime ) ; return $ this -> buildDateTimeInterval ( $ tmpDate , $ closestTime ) ; }

Get the closest business hours date interval after the given date.

@param \DateTime $date The given date.
@return DateTimeInterval

Get the closest business hours date interval after the given date .


private function buildDateTimeInterval(\DateTime $date, TimeIntervalInterface $timeInterval): DateTimeInterval
    {
        $intervalStart = clone $date;
        $intervalEnd = clone $date;

        $intervalStart->setTime(
            $timeInterval->getStart()->getHours(),
            $timeInterval->getStart()->getMinutes(),
            $timeInterval->getStart()->getSeconds()
        );
        $intervalEnd->setTime(
            $timeInterval->getEnd()->getHours(),
            $timeInterval->getEnd()->getMinutes(),
            $timeInterval->getEnd()->getSeconds()
        );

        return new DateTimeInterval($intervalStart, $intervalEnd);
    }

private function buildDateTimeInterval ( \ DateTime $ date , TimeIntervalInterface $ timeInterval ) : DateTimeInterval { $ intervalStart = clone $ date ; $ intervalEnd = clone $ date ; $ intervalStart -> setTime ( $ timeInterval -> getStart ( ) -> getHours ( ) , $ timeInterval -> getStart ( ) -> getMinutes ( ) , $ timeInterval -> getStart ( ) -> getSeconds ( ) ) ; $ intervalEnd -> setTime ( $ timeInterval -> getEnd ( ) -> getHours ( ) , $ timeInterval -> getEnd ( ) -> getMinutes ( ) , $ timeInterval -> getEnd ( ) -> getSeconds ( ) ) ; return new DateTimeInterval ( $ intervalStart , $ intervalEnd ) ; }

Build a new date time interval for a date.

@param \DateTime $date The date.
@param TimeIntervalInterface $timeInterval
@return DateTimeInterval

Build a new date time interval for a date .


private function getDayBefore(int $dayNumber)
    {
        $tmpDayNumber = $dayNumber;

        for ($i = 0; $i < 6; $i++) {
            $tmpDayNumber = (DayInterface::WEEK_DAY_MONDAY === $tmpDayNumber) ? DayInterface::WEEK_DAY_SUNDAY : --$tmpDayNumber;

            if (null !== $day = $this->getDay($tmpDayNumber)) {
                return $day;
            }
        }

        return $this->getDay($dayNumber);
    }

private function getDayBefore ( int $ dayNumber ) { $ tmpDayNumber = $ dayNumber ; for ( $ i = 0 ; $ i < 6 ; $ i ++ ) { $ tmpDayNumber = ( DayInterface :: WEEK_DAY_MONDAY === $ tmpDayNumber ) ? DayInterface :: WEEK_DAY_SUNDAY : -- $ tmpDayNumber ; if ( null !== $ day = $ this -> getDay ( $ tmpDayNumber ) ) { return $ day ; } } return $ this -> getDay ( $ dayNumber ) ; }

Get the business hours day before the day number.

@param integer $dayNumber
@return DayInterface|null

Get the business hours day before the day number .


private function getDayAfter($dayNumber)
    {
        $tmpDayNumber = $dayNumber;

        for ($i = 0; $i < 6; $i++) {
            $tmpDayNumber = (DayInterface::WEEK_DAY_SUNDAY === $tmpDayNumber) ? DayInterface::WEEK_DAY_MONDAY : ++$tmpDayNumber;

            if (null !== $day = $this->getDay($tmpDayNumber)) {
                return $day;
            }
        }

        return $this->getDay($dayNumber);
    }

private function getDayAfter ( $ dayNumber ) { $ tmpDayNumber = $ dayNumber ; for ( $ i = 0 ; $ i < 6 ; $ i ++ ) { $ tmpDayNumber = ( DayInterface :: WEEK_DAY_SUNDAY === $ tmpDayNumber ) ? DayInterface :: WEEK_DAY_MONDAY : ++ $ tmpDayNumber ; if ( null !== $ day = $ this -> getDay ( $ tmpDayNumber ) ) { return $ day ; } } return $ this -> getDay ( $ dayNumber ) ; }

Get the business hours day after the day number.

@param integer $dayNumber
@return DayInterface|null

Get the business hours day after the day number .


function getInfo($role)
    {
        if (empty($GLOBALS['_PEAR_INSTALLER_ROLES'][$role])) {
            return PEAR::raiseError('Unknown Role class: "' . $role . '"');
        }
        return $GLOBALS['_PEAR_INSTALLER_ROLES'][$role];
    }

function
getInfo
(
$
role
)
{
if
(
empty
(
$
GLOBALS
[
'_PEAR_INSTALLER_ROLES'
]
[
$
role
]
)
)
{
return
PEAR
::
raiseError
(
'Unknown Role class: "'
.
$
role
.
'"'
)
;
}
return
$
GLOBALS
[
'_PEAR_INSTALLER_ROLES'
]
[
$
role
]
;
}

Retrieve configuration information about a file role from its XML info

@param string $role Role Classname, as in "PEAR_Installer_Role_Data"
@return array


public function commit()
    {
        if (!$this->getIsActive()) {
            throw new Exception('Failed to commit transaction: transaction was inactive.');
        }

        $connection = $this->getConnection();
        $this->_level--;
        if ($this->_level === 0) {
            Reaction::debug('Commit transaction');
            return $connection->commitTransaction()
                ->thenLazy(function() { $this->closeConnection(); });
        }

        $schema = $this->db->getSchema();
        if ($schema->supportsSavepoint()) {
            Reaction::debug('Release savepoint ' . $this->_level);
            return $connection->releaseSavepoint('LEVEL' . $this->_level);
        } else {
            Reaction::info('Transaction not committed: nested transaction not supported');
        }
        return Reaction\Promise\rejectLazy(null);
    }

Commits a transaction.
@throws Exception if the transaction is not active
@return ExtendedPromiseInterface|LazyPromiseInterface


public function rollBack($final = false)
    {
        if (!$this->getIsActive()) {
            // do nothing if transaction is not active: this could be the transaction is committed
            // but the event handler to "commitTransaction" throw an exception
            return Reaction\Promise\reject(new Exception("There is no active transactions"));
        }

        //Roll back all transaction with save points
        if ($final && $this->_level > 1) {
            $promises = [];
            while ($this->_level > 0) {
                $promises[] = $this->rollBack(false);
            }
            return !empty($promises)
                ? Reaction\Promise\allInOrder($promises)->then(function() { return true; })
                : Reaction\Promise\resolve(true);
        }

        $connection = $this->getConnection();
        $this->_level--;
        if ($this->_level === 0) {
            Reaction::debug('Roll back transaction');
            return $connection->rollBackTransaction()
                ->thenLazy(function() { $this->closeConnection(); });
        }

        $schema = $this->db->getSchema();
        if ($schema->supportsSavepoint()) {
            Reaction::debug('Roll back to savepoint ' . $this->_level);
            return $connection->rollBackSavepoint('LEVEL' . $this->_level);
        } else {
            Reaction::info('Transaction not rolled back: nested transaction not supported');
            // throw an exception to fail the outer transaction
            return Reaction\Promise\reject(new Exception('Roll back failed: nested transaction not supported.'));
        }
    }

Rolls back a transaction.
@param bool $final
@return ExtendedPromiseInterface


public function setIsolationLevel($level)
    {
        if (!$this->getIsActive()) {
            throw new Exception('Failed to set isolation level: transaction was inactive.');
        }
        Reaction::debug('Setting transaction isolation level to ' . $level);
        return $this->getConnection()->setTransactionIsolationLevel($level);
    }

Sets the transaction isolation level for this transaction.

This method can be used to set the isolation level while the transaction is already active.
However this is not supported by all DBMS so you might rather specify the isolation level directly
when calling [[begin()]].
@param string $level The transaction isolation level to use for this transaction.
This can be one of [[READ_UNCOMMITTED]], [[READ_COMMITTED]], [[REPEATABLE_READ]] and [[SERIALIZABLE]] but
also a string containing DBMS specific syntax to be used after `SET TRANSACTION ISOLATION LEVEL`.
@return ExtendedPromiseInterface|LazyPromiseInterface
@throws Exception if the transaction is not active
@see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels

Sets the transaction isolation level for this transaction .


public function getConnection() {
        if (!isset($this->connection)) {
            $this->connection = $this->db->getDedicatedConnection();
        }
        return $this->connection;
    }

public function getConnection ( ) { if ( ! isset ( $ this -> connection ) ) { $ this -> connection = $ this -> db -> getDedicatedConnection ( ) ; } return $ this -> connection ; }

Get DB connection
@return ConnectionInterface


public function setBackend($backend)
    {
        if (!is_string($backend)) {
            throw new Exception\InvalidArgumentException(__METHOD__ . " backend parameter must be a valid string.");
        }

        if (!in_array($backend, $this->supported_backends)) {
            $valid_backends = implode(',', $this->supported_backends);
            throw new Exception\UnsupportedBackendException(__METHOD__ . " Backend '$backend' is not supported, supported backends are '$valid_backends'''");
        }
        $this->backend = $backend;
        return $this;
    }

Set the backend gd of imagick to use

@param string $backend (gd/imagick)

@throws Exception\UnsupportedBackendException
@return \Soluble\Media\Converter\ImageConverter


public function debug(string $message, array $context = []): Logger
    {
        $this->logger->{LogLevel::DEBUG}($message, $context);

        return $this;
    }

public function debug ( string $ message , array $ context = [ ] ) : Logger { $ this -> logger -> { LogLevel :: DEBUG } ( $ message , $ context ) ; return $ this ; }

Log a debug message.

@param string $message The message
@param array  $context [optional] The context

@return \Valkyrja\Logger\Logger


public function info(string $message, array $context = []): Logger
    {
        $this->logger->{LogLevel::INFO}($message, $context);

        return $this;
    }

public function info ( string $ message , array $ context = [ ] ) : Logger { $ this -> logger -> { LogLevel :: INFO } ( $ message , $ context ) ; return $ this ; }

Log an info message.

@param string $message The message
@param array  $context [optional] The context

@return \Valkyrja\Logger\Logger


public function notice(string $message, array $context = []): Logger
    {
        $this->logger->{LogLevel::NOTICE}($message, $context);

        return $this;
    }

public function notice ( string $ message , array $ context = [ ] ) : Logger { $ this -> logger -> { LogLevel :: NOTICE } ( $ message , $ context ) ; return $ this ; }

Log a notice message.

@param string $message The message
@param array  $context [optional] The context

@return \Valkyrja\Logger\Logger


public function warning(string $message, array $context = []): Logger
    {
        $this->logger->{LogLevel::WARNING}($message, $context);

        return $this;
    }

public function warning ( string $ message , array $ context = [ ] ) : Logger { $ this -> logger -> { LogLevel :: WARNING } ( $ message , $ context ) ; return $ this ; }

Log a warning message.

@param string $message The message
@param array  $context [optional] The context

@return \Valkyrja\Logger\Logger


public function error(string $message, array $context = []): Logger
    {
        $this->logger->{LogLevel::ERROR}($message, $context);

        return $this;
    }

public function error ( string $ message , array $ context = [ ] ) : Logger { $ this -> logger -> { LogLevel :: ERROR } ( $ message , $ context ) ; return $ this ; }

Log a error message.

@param string $message The message
@param array  $context [optional] The context

@return \Valkyrja\Logger\Logger


public function critical(string $message, array $context = []): Logger
    {
        $this->logger->{LogLevel::CRITICAL}($message, $context);

        return $this;
    }

public function critical ( string $ message , array $ context = [ ] ) : Logger { $ this -> logger -> { LogLevel :: CRITICAL } ( $ message , $ context ) ; return $ this ; }

Log a critical message.

@param string $message The message
@param array  $context [optional] The context

@return \Valkyrja\Logger\Logger


public function alert(string $message, array $context = []): Logger
    {
        $this->logger->{LogLevel::ALERT}($message, $context);

        return $this;
    }

public function alert ( string $ message , array $ context = [ ] ) : Logger { $ this -> logger -> { LogLevel :: ALERT } ( $ message , $ context ) ; return $ this ; }

Log a alert message.

@param string $message The message
@param array  $context [optional] The context

@return \Valkyrja\Logger\Logger


public function emergency(string $message, array $context = []): Logger
    {
        $this->logger->{LogLevel::EMERGENCY}($message, $context);

        return $this;
    }

public function emergency ( string $ message , array $ context = [ ] ) : Logger { $ this -> logger -> { LogLevel :: EMERGENCY } ( $ message , $ context ) ; return $ this ; }

Log a emergency message.

@param string $message The message
@param array  $context [optional] The context

@return \Valkyrja\Logger\Logger


public function log(LogLevel $level, string $message, array $context = []): Logger
    {
        $this->logger->{$level->getValue()}($message, $context);

        return $this;
    }

public function log ( LogLevel $ level , string $ message , array $ context = [ ] ) : Logger { $ this -> logger -> { $ level -> getValue ( ) } ( $ message , $ context ) ; return $ this ; }

Log a message.

@param LogLevel $level   The log level
@param string   $message The message
@param array    $context [optional] The context

@return \Valkyrja\Logger\Logger


public function getProperty($object, $propertyPath, $required = true)
    {
        if (!$required) {
            try {
                return $this->accessor->getValue($object, $propertyPath);
            } catch(NoSuchIndexException $e) {
                return null;
            }
        }
        return $this->accessor->getValue($object, $propertyPath);
    }

public function getProperty ( $ object , $ propertyPath , $ required = true ) { if ( ! $ required ) { try { return $ this -> accessor -> getValue ( $ object , $ propertyPath ) ; } catch ( NoSuchIndexException $ e ) { return null ; } } return $ this -> accessor -> getValue ( $ object , $ propertyPath ) ; }

Uses PropertyAccess component to return the object property value.

@param mixed  $object
@param string $propertyPath
@param bool   $required

@return mixed

Uses PropertyAccess component to return the object property value .


public function truncateHtml($html, $limit, $endChar = '…')
    {
        $output = new TruncateHtml($html);
        return $output->cut($limit, $endChar);
    }

public function truncateHtml ( $ html , $ limit , $ endChar = '…' ) { $ output = new TruncateHtml ( $ html ) ; return $ output -> cut ( $ limit , $ endChar ) ; }

Returns a truncated html string.

@param string $html
@param int $limit
@param string $endChar

@return string


function PEAR_Installer(&$ui)
    {
        parent::PEAR_Common();
        $this->setFrontendObject($ui);
        $this->debug = $this->config->get('verbose');
    }

function PEAR_Installer ( & $ ui ) { parent :: PEAR_Common ( ) ; $ this -> setFrontendObject ( $ ui ) ; $ this -> debug = $ this -> config -> get ( 'verbose' ) ; }

PEAR_Installer constructor.

@param object $ui user interface object (instance of PEAR_Frontend_*)

@access public


function _deletePackageFiles($package, $channel = false, $backup = false)
    {
        if (!$channel) {
            $channel = 'pear.php.net';
        }

        if (!strlen($package)) {
            return $this->raiseError("No package to uninstall given");
        }

        if (strtolower($package) == 'pear' && $channel == 'pear.php.net') {
            // to avoid race conditions, include all possible needed files
            require_once 'PEAR/Task/Common.php';
            require_once 'PEAR/Task/Replace.php';
            require_once 'PEAR/Task/Unixeol.php';
            require_once 'PEAR/Task/Windowseol.php';
            require_once 'PEAR/PackageFile/v1.php';
            require_once 'PEAR/PackageFile/v2.php';
            require_once 'PEAR/PackageFile/Generator/v1.php';
            require_once 'PEAR/PackageFile/Generator/v2.php';
        }

        $filelist = $this->_registry->packageInfo($package, 'filelist', $channel);
        if ($filelist == null) {
            return $this->raiseError("$channel/$package not installed");
        }

        $ret = array();
        foreach ($filelist as $file => $props) {
            if (empty($props['installed_as'])) {
                continue;
            }

            $path = $props['installed_as'];
            if ($backup) {
                $this->addFileOperation('backup', array($path));
                $ret[] = $path;
            }

            $this->addFileOperation('delete', array($path));
        }

        if ($backup) {
            return $ret;
        }

        return true;
    }

Delete a package's installed files, does not remove empty directories.

@param string package name
@param string channel name
@param bool if true, then files are backed up first
@return bool TRUE on success, or a PEAR error on failure
@access protected

Delete a package s installed files does not remove empty directories .


function addFileOperation($type, $data)
    {
        if (!is_array($data)) {
            return $this->raiseError('Internal Error: $data in addFileOperation'
                . ' must be an array, was ' . gettype($data));
        }

        if ($type == 'chmod') {
            $octmode = decoct($data[0]);
            $this->log(3, "adding to transaction: $type $octmode $data[1]");
        } else {
            $this->log(3, "adding to transaction: $type " . implode(" ", $data));
        }
        $this->file_operations[] = array($type, $data);
    }

Add a file operation to the current file transaction.

@see startFileTransaction()
@param string $type This can be one of:
- rename:  rename a file ($data has 3 values)
- backup:  backup an existing file ($data has 1 value)
- removebackup:  clean up backups created during install ($data has 1 value)
- chmod:   change permissions on a file ($data has 2 values)
- delete:  delete a file ($data has 1 value)
- rmdir:   delete a directory if empty ($data has 1 value)
- installed_as: mark a file as installed ($data has 4 values).
@param array $data For all file operations, this array must contain the
full path to the file or directory that is being operated on.  For
the rename command, the first parameter must be the file to rename,
the second its new name, the third whether this is a PHP extension.

The installed_as operation contains 4 elements in this order:
1. Filename as listed in the filelist element from package.xml
2. Full path to the installed file
3. Full path from the php_dir configuration variable used in this
installation
4. Relative path from the php_dir that this file is installed in

Add a file operation to the current file transaction .


function download($packages, $options, &$config, &$installpackages,
                      &$errors, $installed = false, $willinstall = false, $state = false)
    {
        // trickiness: initialize here
        parent::PEAR_Downloader($this->ui, $options, $config);
        $ret             = parent::download($packages);
        $errors          = $this->getErrorMsgs();
        $installpackages = $this->getDownloadedPackages();
        trigger_error("PEAR Warning: PEAR_Installer::download() is deprecated " .
                      "in favor of PEAR_Downloader class", E_USER_WARNING);
        return $ret;
    }

Download any files and their dependencies, if necessary

@param array a mixed list of package names, local files, or package.xml
@param PEAR_Config
@param array options from the command line
@param array this is the array that will be populated with packages to
install.  Format of each entry:

<code>
array('pkg' => 'package_name', 'file' => '/path/to/local/file',
'info' => array() // parsed package.xml
);
</code>
@param array this will be populated with any error messages
@param false private recursion variable
@param false private recursion variable
@param false private recursion variable
@deprecated in favor of PEAR_Downloader

Download any files and their dependencies if necessary


function setDownloadedPackages(&$pkgs)
    {
        PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
        $err = $this->analyzeDependencies($pkgs);
        PEAR::popErrorHandling();
        if (PEAR::isError($err)) {
            return $err;
        }
        $this->_downloadedPackages = &$pkgs;
    }

function setDownloadedPackages ( & $ pkgs ) { PEAR :: pushErrorHandling ( PEAR_ERROR_RETURN ) ; $ err = $ this -> analyzeDependencies ( $ pkgs ) ; PEAR :: popErrorHandling ( ) ; if ( PEAR :: isError ( $ err ) ) { return $ err ; } $ this -> _downloadedPackages = & $ pkgs ; }

Set the list of PEAR_Downloader_Package objects to allow more sane
dependency validation
@param array


public function isValidPoint(PointInterface $a)
    {
        return (bool) (
            $this->getSegmentAB()->isValidPoint($a) ||
            $this->getSegmentBC()->isValidPoint($a) ||
            $this->getSegmentCA()->isValidPoint($a)
        );
    }

public function isValidPoint ( PointInterface $ a ) { return ( bool ) ( $ this -> getSegmentAB ( ) -> isValidPoint ( $ a ) || $ this -> getSegmentBC ( ) -> isValidPoint ( $ a ) || $ this -> getSegmentCA ( ) -> isValidPoint ( $ a ) ) ; }

Test if point A is in one of the triangle's segments

@param   \Maths\PointInterface   $a
@return  bool

Test if point A is in one of the triangle s segments


protected function _createIteratingException($message = null, $code = null, RootException $previous = null)
    {
        return new IteratingException($message, $code, $previous);
    }

protected function _createIteratingException ( $ message = null , $ code = null , RootException $ previous = null ) { return new IteratingException ( $ message , $ code , $ previous ) ; }

Creates a new iterating exception instance.

@since [*next-version*]

@param string|Stringable|null $message  The error message, if any.
@param int|null               $code     The error code, if any.
@param RootException|null     $previous The previous exception for chaining, if any.

@return IteratingException The created exception instance.

Creates a new iterating exception instance .


public function registerComponents(Container $container)
    {
        $this->bindClient($container);

        $this->bindCommandBus($container);

        $container->singleton('Ordercloud\Support\ExceptionGenerators\ExceptionGeneratorService', function () use ($container)
        {
            return new ChainedExceptionGeneratorService($container, [
                'Ordercloud\Requests\Orders\Exceptions\OrderExceptionGenerator',
                'Ordercloud\Requests\Payments\Exceptions\PaymentExceptionGenerator',
                'Ordercloud\Requests\Exceptions\RequestExceptionGenerator', // Always chain default handler last
            ]);
        });

        $container->singleton('Ordercloud\Support\Parser');

        $container->singleton('Ordercloud\Services\UserService');
        $container->singleton('Ordercloud\Services\OrganisationService');

        $container->singleton('Ordercloud\Ordercloud', function () use ($container)
        {
            return new Ordercloud($container);
        });
    }

Register all ordercloud components on the specified Container.

@param Container $container

Register all ordercloud components on the specified Container .


private function addArrayAttributes($attribute, array $values)
    {
        array_map(function ($value) use ($attribute) {
            $this->attributes->put($attribute, $value);
        }, $values);

        return $this;
    }

private function addArrayAttributes ( $ attribute , array $ values ) { array_map ( function ( $ value ) use ( $ attribute ) { $ this -> attributes -> put ( $ attribute , $ value ) ; } , $ values ) ; return $ this ; }

Add a array values to attribute collection.

@param string $attribute
@param array  $values

@return self

Add a array values to attribute collection .


private function changeClasses($method, $class)
    {
        array_map(function ($class) use ($method) {
            if ($method === 'add') {
                return $this->classes->put($class, $class);
            }

            return $this->classes->remove($class);
        }, explode(' ', $class));

        return $this;
    }

private
function
changeClasses
(
$
method
,
$
class
)
{
array_map
(
function
(
$
class
)
use
(
$
method
)
{
if
(
$
method
===
'add'
)
{
return
$
this
->
classes
->
put
(
$
class
,
$
class
)
;
}
return
$
this
->
classes
->
remove
(
$
class
)
;
}
,
explode
(
' '
,
$
class
)
)
;
return
$
this
;
}

Change class collection values.

@param string $method
@param string $class

@return self


private function parseClasses()
    {
        if ($this->classes->count() > 0) {
            $this->attributes->put('class', implode(' ', $this->classes->all()));
        }

        return $this;
    }

private
function
parseClasses
(
)
{
if
(
$
this
->
classes
->
count
(
)
>
0
)
{
$
this
->
attributes
->
put
(
'class'
,
implode
(
' '
,
$
this
->
classes
->
all
(
)
)
)
;
}
return
$
this
;
}

Add classes from collection to attributes collection.

@return self

Add classes from collection to attributes collection .


public function json()
    {
        /*
         * TODO Remove in Yii 2.1
         *
         * Disabled due to bug in MySQL extension
         * @link https://bugs.php.net/bug.php?id=70384
         */
        if (version_compare(PHP_VERSION, '5.6', '<') && $this->getDb()->getDriverName() === 'mysql') {
            throw new \Reaction\Exceptions\Exception('JSON column type is not supported in PHP < 5.6');
        }

        return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_JSON);
    }

Creates a JSON column.
@return ColumnSchemaBuilder the column instance which can be further customized.
@throws \Reaction\Exceptions\Exception


public function bindIf( $abstract, $concrete = NULL, $shared = FALSE )
    {
        if ( !$this->bound( $abstract ) )
        {
            $this->bind( $abstract, $concrete, $shared );
        }

        return $this;
    }

public function bindIf ( $ abstract , $ concrete = NULL , $ shared = FALSE ) { if ( ! $ this -> bound ( $ abstract ) ) { $ this -> bind ( $ abstract , $ concrete , $ shared ) ; } return $ this ; }

Register a binding if it hasn't already been registered.

@param  string              $abstract
@param  Closure|string|null $concrete
@param  bool                $shared

@return IContainer

Register a binding if it hasn t already been registered .


public function bindShared( $abstract, Closure $closure )
    {
        $this->bind( $abstract, $this->share( $closure ), TRUE );

        return $this;
    }

public function bindShared ( $ abstract , Closure $ closure ) { $ this -> bind ( $ abstract , $ this -> share ( $ closure ) , TRUE ) ; return $ this ; }

Bind a shared Closure into the container.

@param  string  $abstract
@param  Closure $closure

@return IContainer

Bind a shared Closure into the container .


public function rebinding( $abstract, Closure $callback )
    {
        $this->reboundCallbacks[ $abstract ][ ] = $callback;

        if ( $this->bound( $abstract ) )
        {
            return $this->make( $abstract );
        }

        return $this;
    }

public function rebinding ( $ abstract , Closure $ callback ) { $ this -> reboundCallbacks [ $ abstract ] [ ] = $ callback ; if ( $ this -> bound ( $ abstract ) ) { return $ this -> make ( $ abstract ) ; } return $ this ; }

Bind a new callback to an abstract's rebind event.

@param  string  $abstract
@param  Closure $callback

@return mixed

Bind a new callback to an abstract s rebind event .


public function isShared( $abstract )
    {
        if ( isset( $this->bindings[ $abstract ][ 'shared' ] ) )
        {
            $shared = $this->bindings[ $abstract ][ 'shared' ];
        }
        else
        {
            $shared = FALSE;
        }

        return isset( $this->instances[ $abstract ] ) || TRUE === $shared;
    }

public function isShared ( $ abstract ) { if ( isset ( $ this -> bindings [ $ abstract ] [ 'shared' ] ) ) { $ shared = $ this -> bindings [ $ abstract ] [ 'shared' ] ; } else { $ shared = FALSE ; } return isset ( $ this -> instances [ $ abstract ] ) || TRUE === $ shared ; }

Determine if a given type is shared.

@param  string $abstract

@return bool


protected function getClosure( $abstract, $concrete )
    {
        return function ( $c, $parameters = [ ] ) use ( $abstract, $concrete )
        {
            $method = ( $abstract == $concrete ) ? 'build' : 'make';

            return $c->$method( $concrete, $parameters );
        };
    }

protected function getClosure ( $ abstract , $ concrete ) { return function ( $ c , $ parameters = [ ] ) use ( $ abstract , $ concrete ) { $ method = ( $ abstract == $ concrete ) ? 'build' : 'make' ; return $ c -> $ method ( $ concrete , $ parameters ) ; } ; }

Get a Closure to be used when building a type.

@param string $abstract
@param string $concrete

@return Closure

Get a Closure to be used when building a type .


protected function addDependencyForCallParameter( ReflectionParameter $parameter, array &$parameters, array &$dependencies )
    {
        if ( array_key_exists( $parameter->name, $parameters ) )
        {
            $dependencies[ ] = $parameters[ $parameter->name ];
        }
        elseif ( $parameter->getClass() )
        {
            $dependencies[ ] = $this->make( $parameter->getClass()->name );
        }
        elseif ( $parameter->isDefaultValueAvailable() )
        {
            $dependencies[ ] = $parameter->getDefaultValue();
        }
    }

protected function addDependencyForCallParameter ( ReflectionParameter $ parameter , array & $ parameters , array & $ dependencies ) { if ( array_key_exists ( $ parameter -> name , $ parameters ) ) { $ dependencies [ ] = $ parameters [ $ parameter -> name ] ; } elseif ( $ parameter -> getClass ( ) ) { $ dependencies [ ] = $ this -> make ( $ parameter -> getClass ( ) -> name ) ; } elseif ( $ parameter -> isDefaultValueAvailable ( ) ) { $ dependencies [ ] = $ parameter -> getDefaultValue ( ) ; } }

Get the dependency for the given call parameter.

@param ReflectionParameter $parameter
@param array               $parameters
@param array               $dependencies

Get the dependency for the given call parameter .


public function getContextualConcrete( $abstract )
    {
        if ( isset( $this->contextual[ Util::last( $this->buildStack ) ][ $abstract ] ) )
        {
            return $this->contextual[ Util::last( $this->buildStack ) ][ $abstract ];
        }

        return NULL;
    }

public function getContextualConcrete ( $ abstract ) { if ( isset ( $ this -> contextual [ Util :: last ( $ this -> buildStack ) ] [ $ abstract ] ) ) { return $ this -> contextual [ Util :: last ( $ this -> buildStack ) ] [ $ abstract ] ; } return NULL ; }

Get the contextual concrete binding for the given abstract.

@param string $abstract

@return string

Get the contextual concrete binding for the given abstract .


public function requestMiddleware(Request $request, array $middleware = null)
    {
        // Set the middleware to any middleware passed or the base middleware
        $middleware = $middleware ?? self::$middleware;

        $modifiedRequest = $request;

        // Get the application
        $app = $this->getApplication();

        // Iterate through the middleware
        foreach ($middleware as $item) {
            // If the middleware is a group
            if ($this->isMiddlewareGroup($item)) {
                // Recurse into that middleware group
                $this->requestMiddleware(
                    $request,
                    $this->getMiddlewareGroup($item)
                );

                continue;
            }

            /* @var \Valkyrja\Http\Middleware\Middleware $item */
            $modifiedRequest = $item::before($request);

            if ($modifiedRequest instanceof Response) {
                return $modifiedRequest;
            }

            // Set the returned request in the container
            $app->container()->singleton(Request::class, $modifiedRequest);
        }

        return $modifiedRequest;
    }

Dispatch middleware.

@param Request $request    The request
@param array   $middleware [optional] The middleware to dispatch

@return mixed