public function findByFilters($filters, $sort = [], $limit = null, $offset = null)
    {
        $queryBuilder = $this->createQueryBuilder('dynamic');

        // Add filter.
        $this->addFilter($queryBuilder, $filters);

        // Add sorting.
        if (!empty($sort)) {
            foreach ($sort as $key => $value) {
                $queryBuilder->addOrderBy('dynamic.' . $key, $value);
            }
        }

        // Add limit and offset.
        if ($limit) {
            $queryBuilder->setMaxResults($limit);
        }

        if ($offset) {
            $queryBuilder->setFirstResult($offset);
        }

        return $queryBuilder->getQuery()->getResult();
    }

public
function
findByFilters
(
$
filters
,
$
sort
=
[
]
,
$
limit
=
,
$
offset
=
)
{
$
queryBuilder
=
$
this
->
createQueryBuilder
(
'dynamic'
)
;
// Add filter.
$
this
->
addFilter
(
$
queryBuilder
,
$
filters
)
;
// Add sorting.
if
(
!
empty
(
$
sort
)
)
{
foreach
(
$
sort
as
$
key
=>
$
value
)
{
$
queryBuilder
->
addOrderBy
(
'dynamic.'
.
$
key
,
$
value
)
;
}
}
// Add limit and offset.
if
(
$
limit
)
{
$
queryBuilder
->
setMaxResults
(
$
limit
)
;
}
if
(
$
offset
)
{
$
queryBuilder
->
setFirstResult
(
$
offset
)
;
}
return
$
queryBuilder
->
getQuery
(
)
->
getResult
(
)
;
}

Finds dynamic entries by the given parameters.

@param array $filters
@param array $sort
@param int|null $limit
@param int|null $offset

@return array

Finds dynamic entries by the given parameters .


public function countByFilters($filters)
    {
        $queryBuilder = $this->createQueryBuilder('dynamic');
        $queryBuilder->select($queryBuilder->expr()->count('dynamic.id'));
        $this->addFilter($queryBuilder, $filters);

        return (int) $queryBuilder->getQuery()->getSingleScalarResult();
    }

public function countByFilters ( $ filters ) { $ queryBuilder = $ this -> createQueryBuilder ( 'dynamic' ) ; $ queryBuilder -> select ( $ queryBuilder -> expr ( ) -> count ( 'dynamic.id' ) ) ; $ this -> addFilter ( $ queryBuilder , $ filters ) ; return ( int ) $ queryBuilder -> getQuery ( ) -> getSingleScalarResult ( ) ; }

Returns the number of found entities.

@param array $filters

@return int


protected function addFilter($queryBuilder, $filters)
    {
        $fromDate = null;
        $toDate = null;
        $search = null;
        $searchFields = null;

        if (isset($filters['fromDate'])) {
            $fromDate = $filters['fromDate'];
            unset($filters['fromDate']);
        }

        if (isset($filters['toDate'])) {
            $toDate = $filters['toDate'];
            unset($filters['toDate']);
        }

        if (isset($filters['search'])) {
            $search = $filters['search'];
            unset($filters['search']);
        }

        if (isset($filters['searchFields'])) {
            $searchFields = $filters['searchFields'];
            unset($filters['searchFields']);
        }

        $this->addSearchFilter($queryBuilder, $search, $searchFields);
        $this->addDateRangeFilter($queryBuilder, $fromDate, $toDate);

        $counter = 0;
        foreach ($filters as $key => $value) {
            $queryBuilder->andWhere($queryBuilder->expr()->eq('dynamic.' . $key, ':value' . $counter));
            $queryBuilder->setParameter('value' . $counter, $value);

            ++$counter;
        }
    }

protected function addFilter ( $ queryBuilder , $ filters ) { $ fromDate = null ; $ toDate = null ; $ search = null ; $ searchFields = null ; if ( isset ( $ filters [ 'fromDate' ] ) ) { $ fromDate = $ filters [ 'fromDate' ] ; unset ( $ filters [ 'fromDate' ] ) ; } if ( isset ( $ filters [ 'toDate' ] ) ) { $ toDate = $ filters [ 'toDate' ] ; unset ( $ filters [ 'toDate' ] ) ; } if ( isset ( $ filters [ 'search' ] ) ) { $ search = $ filters [ 'search' ] ; unset ( $ filters [ 'search' ] ) ; } if ( isset ( $ filters [ 'searchFields' ] ) ) { $ searchFields = $ filters [ 'searchFields' ] ; unset ( $ filters [ 'searchFields' ] ) ; } $ this -> addSearchFilter ( $ queryBuilder , $ search , $ searchFields ) ; $ this -> addDateRangeFilter ( $ queryBuilder , $ fromDate , $ toDate ) ; $ counter = 0 ; foreach ( $ filters as $ key => $ value ) { $ queryBuilder -> andWhere ( $ queryBuilder -> expr ( ) -> eq ( 'dynamic.' . $ key , ':value' . $ counter ) ) ; $ queryBuilder -> setParameter ( 'value' . $ counter , $ value ) ; ++ $ counter ; } }

Adds the filters from the given array to the QueryBuilder.

@param QueryBuilder $queryBuilder
@param array $filters

Adds the filters from the given array to the QueryBuilder .


protected function addSearchFilter($queryBuilder, $search, $searchFields)
    {
        if (empty($search) || empty($searchFields)) {
            return;
        }

        $terms = explode(' ', $search);

        // Search each term in each search field
        foreach ($terms as $counter => $term) {
            $expressions = [];

            foreach ($searchFields as $searchField) {
                $expressions[] = $queryBuilder->expr()->like(
                    'dynamic.' . $searchField,
                    ':searchTerm' . $counter
                );
            }

            $queryBuilder->andWhere(call_user_func_array([$queryBuilder->expr(), 'orX'], $expressions));
            $queryBuilder->setParameter('searchTerm' . $counter, '%' . $term . '%');
        }
    }

Depending on the given search term, this function filters the result based on search fields.

@param QueryBuilder $queryBuilder
@param string $search
@param string[] $searchFields

Depending on the given search term this function filters the result based on search fields .


protected function addDateRangeFilter($queryBuilder, $fromDate, $toDate)
    {
        if ($fromDate && $toDate) {
            $queryBuilder->andWhere($queryBuilder->expr()->between('dynamic.created', ':fromDate', ':toDate'));
            $queryBuilder->setParameter('fromDate', $fromDate);
            $queryBuilder->setParameter('toDate', $toDate);
        } elseif ($fromDate) {
            $queryBuilder->andWhere($queryBuilder->expr()->gte('dynamic.created', ':fromDate'));
            $queryBuilder->setParameter('fromDate', $fromDate);
        } elseif ($toDate) {
            $queryBuilder->andWhere($queryBuilder->expr()->lte('dynamic.created', ':toDate'));
            $queryBuilder->setParameter('toDate', $toDate);
        }
    }

protected function addDateRangeFilter ( $ queryBuilder , $ fromDate , $ toDate ) { if ( $ fromDate && $ toDate ) { $ queryBuilder -> andWhere ( $ queryBuilder -> expr ( ) -> between ( 'dynamic.created' , ':fromDate' , ':toDate' ) ) ; $ queryBuilder -> setParameter ( 'fromDate' , $ fromDate ) ; $ queryBuilder -> setParameter ( 'toDate' , $ toDate ) ; } elseif ( $ fromDate ) { $ queryBuilder -> andWhere ( $ queryBuilder -> expr ( ) -> gte ( 'dynamic.created' , ':fromDate' ) ) ; $ queryBuilder -> setParameter ( 'fromDate' , $ fromDate ) ; } elseif ( $ toDate ) { $ queryBuilder -> andWhere ( $ queryBuilder -> expr ( ) -> lte ( 'dynamic.created' , ':toDate' ) ) ; $ queryBuilder -> setParameter ( 'toDate' , $ toDate ) ; } }

Depending on the given dates, this function filters the result based on the created date.

@param QueryBuilder $queryBuilder
@param string $fromDate
@param string $toDate

Depending on the given dates this function filters the result based on the created date .


public function getField($key)
    {
        if (property_exists($this, $key)) {
            if (in_array($key, self::$ARRAY_TYPES)) {
                if (!is_string($this->$key)) {
                    return;
                }

                return json_decode($this->$key, true);
            }

            return $this->$key;
        }

        $array = $this->getData();

        if (isset($array[$key])) {
            return $array[$key];
        }
    }

public function getField ( $ key ) { if ( property_exists ( $ this , $ key ) ) { if ( in_array ( $ key , self :: $ ARRAY_TYPES ) ) { if ( ! is_string ( $ this -> $ key ) ) { return ; } return json_decode ( $ this -> $ key , true ) ; } return $ this -> $ key ; } $ array = $ this -> getData ( ) ; if ( isset ( $ array [ $ key ] ) ) { return $ array [ $ key ] ; } }

Get field.

@param string $key

@return string|array


public function getFields($hideHidden = false)
    {
        $entry = [];

        if (!$this->form) {
            return [];
        }

        foreach ($this->form->getFields() as $field) {
            if ($hideHidden && in_array($field->getType(), self::$HIDDEN_TYPES)) {
                continue;
            }

            $entry[$field->getKey()] = $this->getField($field->getKey());
        }

        return $entry;
    }

public function getFields ( $ hideHidden = false ) { $ entry = [ ] ; if ( ! $ this -> form ) { return [ ] ; } foreach ( $ this -> form -> getFields ( ) as $ field ) { if ( $ hideHidden && in_array ( $ field -> getType ( ) , self :: $ HIDDEN_TYPES ) ) { continue ; } $ entry [ $ field -> getKey ( ) ] = $ this -> getField ( $ field -> getKey ( ) ) ; } return $ entry ; }

Get fields.

@param bool $hideHidden

@return array


public function buildByDynamic(Dynamic $dynamic)
    {
        $config = $this->create($dynamic->getLocale());
        $config->setFileFields($this->getFileFieldsByDynamic($dynamic));

        $adminMailConfiguration = $this->buildAdminMailConfigurationByDynamic($dynamic);
        $websiteMailConfiguration = $this->buildWebsiteMailConfigurationByDynamic($dynamic);

        $config->setAdminMailConfiguration($adminMailConfiguration);
        $config->setWebsiteMailConfiguration($websiteMailConfiguration);

        return $config;
    }

public function buildByDynamic ( Dynamic $ dynamic ) { $ config = $ this -> create ( $ dynamic -> getLocale ( ) ) ; $ config -> setFileFields ( $ this -> getFileFieldsByDynamic ( $ dynamic ) ) ; $ adminMailConfiguration = $ this -> buildAdminMailConfigurationByDynamic ( $ dynamic ) ; $ websiteMailConfiguration = $ this -> buildWebsiteMailConfigurationByDynamic ( $ dynamic ) ; $ config -> setAdminMailConfiguration ( $ adminMailConfiguration ) ; $ config -> setWebsiteMailConfiguration ( $ websiteMailConfiguration ) ; return $ config ; }

Build by dynamic entity.

@param Dynamic $dynamic

@return FormConfigurationInterface


public function buildByType(AbstractType $type, $formData, $locale, $attributes)
    {
        $config = $this->create($locale);
        $config->setFileFields(array_fill_keys($type->getFileFields(), $type->getCollectionId()));

        $attributes['form'] = [
            'data' => $formData,
        ];

        $adminMailConfiguration = $this->buildAdminMailConfigurationByTypeAndData(
            $type,
            $formData,
            $locale,
            $attributes
        );
        $websiteMailConfiguration = $this->buildWebsiteMailConfigurationByTypeAndData(
            $type,
            $formData,
            $locale,
            $attributes
        );

        $config->setAdminMailConfiguration($adminMailConfiguration);
        $config->setWebsiteMailConfiguration($websiteMailConfiguration);

        return $config;
    }

Build by type.

@param AbstractType $type
@param mixed $formData
@param string $locale
@param array $attributes

@return FormConfigurationInterface


private function buildAdminMailConfigurationByDynamic(Dynamic $dynamic)
    {
        $form = $dynamic->getForm();
        $locale = $dynamic->getLocale();
        $translation = $form->getTranslation($locale);

        if ($translation->getDeactivateNotifyMails()) {
            return null;
        }

        $adminMailConfiguration = $this->createMailConfiguration($locale);

        $adminMailConfiguration->setSubject($translation->getSubject());
        $adminMailConfiguration->setFrom(
            $this->getEmail($translation->getFromEmail(), $translation->getFromName())
        );

        // Set Receivers for the email.
        $toList = $this->getEmail($translation->getToEmail(), $translation->getToName()) ?: [];
        $ccList = [];
        $bccList = [];

        foreach ($translation->getReceivers() as $receiver) {
            $email = $this->getEmail($receiver->getEmail(), $receiver->getName());

            if (MailConfigurationInterface::TYPE_TO == $receiver->getType()) {
                $toList = array_merge($toList, $email);
            } elseif (MailConfigurationInterface::TYPE_CC == $receiver->getType()) {
                $ccList = array_merge($ccList, $email);
            } elseif (MailConfigurationInterface::TYPE_BCC == $receiver->getType()) {
                $bccList = array_merge($bccList, $email);
            }
        }

        $adminMailConfiguration->setTo(array_filter($toList));
        $adminMailConfiguration->setCc(array_filter($ccList));
        $adminMailConfiguration->setBcc(array_filter($bccList));

        if ($translation->getReplyTo()) {
            $adminMailConfiguration->setReplyTo($this->getEmailFromDynamic($dynamic));
        }

        // Set attachment configuration.
        $adminMailConfiguration->setAddAttachments($translation->getSendAttachments());

        // Set template.
        $adminMailConfiguration->setTemplate($this->mailAdminTemplate);
        $adminMailConfiguration->setTemplateAttributes($this->getTemplateAttributesFromDynamic($dynamic));

        return $adminMailConfiguration;
    }

private
function
buildAdminMailConfigurationByDynamic
(
Dynamic
$
dynamic
)
{
$
form
=
$
dynamic
->
getForm
(
)
;
$
locale
=
$
dynamic
->
getLocale
(
)
;
$
translation
=
$
form
->
getTranslation
(
$
locale
)
;
if
(
$
translation
->
getDeactivateNotifyMails
(
)
)
{
return
;
}
$
adminMailConfiguration
=
$
this
->
createMailConfiguration
(
$
locale
)
;
$
adminMailConfiguration
->
setSubject
(
$
translation
->
getSubject
(
)
)
;
$
adminMailConfiguration
->
setFrom
(
$
this
->
getEmail
(
$
translation
->
getFromEmail
(
)
,
$
translation
->
getFromName
(
)
)
)
;
// Set Receivers for the email.
$
toList
=
$
this
->
getEmail
(
$
translation
->
getToEmail
(
)
,
$
translation
->
getToName
(
)
)
:
[
]
;
$
ccList
=
[
]
;
$
bccList
=
[
]
;
foreach
(
$
translation
->
getReceivers
(
)
as
$
receiver
)
{
$
email
=
$
this
->
getEmail
(
$
receiver
->
getEmail
(
)
,
$
receiver
->
getName
(
)
)
;
if
(
MailConfigurationInterface
::
TYPE_TO
==
$
receiver
->
getType
(
)
)
{
$
toList
=
array_merge
(
$
toList
,
$
email
)
;
}
elseif
(
MailConfigurationInterface
::
TYPE_CC
==
$
receiver
->
getType
(
)
)
{
$
ccList
=
array_merge
(
$
ccList
,
$
email
)
;
}
elseif
(
MailConfigurationInterface
::
TYPE_BCC
==
$
receiver
->
getType
(
)
)
{
$
bccList
=
array_merge
(
$
bccList
,
$
email
)
;
}
}
$
adminMailConfiguration
->
setTo
(
array_filter
(
$
toList
)
)
;
$
adminMailConfiguration
->
setCc
(
array_filter
(
$
ccList
)
)
;
$
adminMailConfiguration
->
setBcc
(
array_filter
(
$
bccList
)
)
;
if
(
$
translation
->
getReplyTo
(
)
)
{
$
adminMailConfiguration
->
setReplyTo
(
$
this
->
getEmailFromDynamic
(
$
dynamic
)
)
;
}
// Set attachment configuration.
$
adminMailConfiguration
->
setAddAttachments
(
$
translation
->
getSendAttachments
(
)
)
;
// Set template.
$
adminMailConfiguration
->
setTemplate
(
$
this
->
mailAdminTemplate
)
;
$
adminMailConfiguration
->
setTemplateAttributes
(
$
this
->
getTemplateAttributesFromDynamic
(
$
dynamic
)
)
;
return
$
adminMailConfiguration
;
}

Build admin mail configuration by dynamic entity.

@param Dynamic $dynamic

@return MailConfiguration|null

Build admin mail configuration by dynamic entity .


private function buildWebsiteMailConfigurationByDynamic(Dynamic $dynamic)
    {
        $form = $dynamic->getForm();
        $locale = $dynamic->getLocale();
        $translation = $form->getTranslation($locale);

        if ($translation->getDeactivateCustomerMails()) {
            return null;
        }

        $websiteMailConfiguration = $this->createMailConfiguration($locale);

        $websiteMailConfiguration->setSubject($translation->getSubject());
        $websiteMailConfiguration->setFrom(
            $this->getEmail($translation->getFromEmail(), $translation->getFromName())
        );
        $websiteMailConfiguration->setTo($this->getEmailFromDynamic($dynamic));

        // Set attachment configuration.
        $websiteMailConfiguration->setAddAttachments($translation->getSendAttachments());

        // Set template.
        $websiteMailConfiguration->setTemplate($this->mailWebsiteTemplate);
        $websiteMailConfiguration->setTemplateAttributes($this->getTemplateAttributesFromDynamic($dynamic));

        return $websiteMailConfiguration;
    }

private
function
buildWebsiteMailConfigurationByDynamic
(
Dynamic
$
dynamic
)
{
$
form
=
$
dynamic
->
getForm
(
)
;
$
locale
=
$
dynamic
->
getLocale
(
)
;
$
translation
=
$
form
->
getTranslation
(
$
locale
)
;
if
(
$
translation
->
getDeactivateCustomerMails
(
)
)
{
return
;
}
$
websiteMailConfiguration
=
$
this
->
createMailConfiguration
(
$
locale
)
;
$
websiteMailConfiguration
->
setSubject
(
$
translation
->
getSubject
(
)
)
;
$
websiteMailConfiguration
->
setFrom
(
$
this
->
getEmail
(
$
translation
->
getFromEmail
(
)
,
$
translation
->
getFromName
(
)
)
)
;
$
websiteMailConfiguration
->
setTo
(
$
this
->
getEmailFromDynamic
(
$
dynamic
)
)
;
// Set attachment configuration.
$
websiteMailConfiguration
->
setAddAttachments
(
$
translation
->
getSendAttachments
(
)
)
;
// Set template.
$
websiteMailConfiguration
->
setTemplate
(
$
this
->
mailWebsiteTemplate
)
;
$
websiteMailConfiguration
->
setTemplateAttributes
(
$
this
->
getTemplateAttributesFromDynamic
(
$
dynamic
)
)
;
return
$
websiteMailConfiguration
;
}

Build website mail configuration by form translation.

@param Dynamic $dynamic

@return MailConfiguration|null

Build website mail configuration by form translation .


private function getFileFieldsByDynamic(Dynamic $dynamic)
    {
        $form = $dynamic->getForm();

        $fields = $form->getFieldsByType(Dynamic::TYPE_ATTACHMENT);

        if (0 === count($fields)) {
            return [];
        }

        $collectionId = $this->getCollectionIdByDynamic($dynamic);

        $fileFields = [];
        foreach ($fields as $field) {
            $fileFields[$field->getKey()] = $collectionId;
        }

        return $fileFields;
    }

private function getFileFieldsByDynamic ( Dynamic $ dynamic ) { $ form = $ dynamic -> getForm ( ) ; $ fields = $ form -> getFieldsByType ( Dynamic :: TYPE_ATTACHMENT ) ; if ( 0 === count ( $ fields ) ) { return [ ] ; } $ collectionId = $ this -> getCollectionIdByDynamic ( $ dynamic ) ; $ fileFields = [ ] ; foreach ( $ fields as $ field ) { $ fileFields [ $ field -> getKey ( ) ] = $ collectionId ; } return $ fileFields ; }

Get file fields by dynamic.

@param Dynamic $dynamic

@return int[]


private function getCollectionIdByDynamic(Dynamic $dynamic)
    {
        $form = $dynamic->getForm();

        return $this->collectionStrategy->getCollectionId(
            $form->getId(),
            $form->getTranslation($dynamic->getLocale(), false, true)->getTitle(),
            $dynamic->getType(),
            $dynamic->getTypeId(),
            $dynamic->getLocale()
        );
    }

private function getCollectionIdByDynamic ( Dynamic $ dynamic ) { $ form = $ dynamic -> getForm ( ) ; return $ this -> collectionStrategy -> getCollectionId ( $ form -> getId ( ) , $ form -> getTranslation ( $ dynamic -> getLocale ( ) , false , true ) -> getTitle ( ) , $ dynamic -> getType ( ) , $ dynamic -> getTypeId ( ) , $ dynamic -> getLocale ( ) ) ; }

Get collection id by dynamic.

@param Dynamic $dynamic

@return array|int


private function getEmailFromDynamic(Dynamic $dynamic)
    {
        $emails = $dynamic->getFieldsByType(Dynamic::TYPE_EMAIL);
        $email = reset($emails);

        return $this->getEmail($email);
    }

private function getEmailFromDynamic ( Dynamic $ dynamic ) { $ emails = $ dynamic -> getFieldsByType ( Dynamic :: TYPE_EMAIL ) ; $ email = reset ( $ emails ) ; return $ this -> getEmail ( $ email ) ; }

Get email from dynamic.

@param Dynamic $dynamic

@return array|null


private function getEmail($email, $name = null)
    {
        if (!$email) {
            return null;
        }

        if (!$name) {
            $name = $email;
        }

        return [$email => $name];
    }

private function getEmail ( $ email , $ name = null ) { if ( ! $ email ) { return null ; } if ( ! $ name ) { $ name = $ email ; } return [ $ email => $ name ] ; }

Get email.

@param string $email
@param string $name

@return array|null


protected function buildForm($id, $type, $typeId, $locale, $name)
    {
        $request = $this->requestStack->getCurrentRequest();

        // Load Form entity
        $formEntity = $this->loadFormEntity($id, $locale);

        if (!$formEntity) {
            return;
        }

        $webspaceKey = $this->getWebspaceKey();

        // Create Form
        $form = $this->createForm(
            $name,
            $type,
            $typeId,
            $locale,
            $formEntity,
            $webspaceKey
        );

        // Handle request
        $form->handleRequest($request);

        return $form;
    }

protected
function
buildForm
(
$
id
,
$
type
,
$
typeId
,
$
locale
,
$
name
)
{
$
request
=
$
this
->
requestStack
->
getCurrentRequest
(
)
;
// Load Form entity
$
formEntity
=
$
this
->
loadFormEntity
(
$
id
,
$
locale
)
;
if
(
!
$
formEntity
)
{
return
;
}
$
webspaceKey
=
$
this
->
getWebspaceKey
(
)
;
// Create Form
$
form
=
$
this
->
createForm
(
$
name
,
$
type
,
$
typeId
,
$
locale
,
$
formEntity
,
$
webspaceKey
)
;
// Handle request
$
form
->
handleRequest
(
$
request
)
;
return
$
form
;
}

Returns formType and the built form.

@param int $id
@param string $type
@param string $typeId
@param string $locale
@param string $name

@return FormInterface


private function createForm($name, $type, $typeId, $locale, $formEntity, $webspaceKey)
    {
        $defaults = $this->getDefaults($formEntity, $locale);
        $typeName = $this->titleProviderPool->get($type)->getTitle($typeId);

        $recaptchaFields = $formEntity->getFieldsByType('recaptcha');
        $csrfTokenProtection = true;

        if (count($recaptchaFields)) {
            $csrfTokenProtection = false;
        }

        return $this->formFactory->createNamed(
            'dynamic_' . $name . $formEntity->getId(),
            DynamicFormType::class,
            new Dynamic($type, $typeId, $locale, $formEntity, $defaults, $webspaceKey, $typeName),
            [
                'formEntity' => $formEntity,
                'locale' => $locale,
                'type' => $type,
                'typeId' => $typeId,
                'csrf_protection' => $csrfTokenProtection,
                'name' => $name,
                'block_name' => 'dynamic_' . $name,
            ]
        );
    }

private function createForm ( $ name , $ type , $ typeId , $ locale , $ formEntity , $ webspaceKey ) { $ defaults = $ this -> getDefaults ( $ formEntity , $ locale ) ; $ typeName = $ this -> titleProviderPool -> get ( $ type ) -> getTitle ( $ typeId ) ; $ recaptchaFields = $ formEntity -> getFieldsByType ( 'recaptcha' ) ; $ csrfTokenProtection = true ; if ( count ( $ recaptchaFields ) ) { $ csrfTokenProtection = false ; } return $ this -> formFactory -> createNamed ( 'dynamic_' . $ name . $ formEntity -> getId ( ) , DynamicFormType :: class , new Dynamic ( $ type , $ typeId , $ locale , $ formEntity , $ defaults , $ webspaceKey , $ typeName ) , [ 'formEntity' => $ formEntity , 'locale' => $ locale , 'type' => $ type , 'typeId' => $ typeId , 'csrf_protection' => $ csrfTokenProtection , 'name' => $ name , 'block_name' => 'dynamic_' . $ name , ] ) ; }

Create form.

@param string $name
@param string $type
@param string $typeId
@param string $locale
@param Form $formEntity
@param string $webspaceKey

@return FormInterface


private function loadFormEntity($id, $locale)
    {
        $formEntity = $this->formRepository->loadById($id, $locale);

        if (!$formEntity) {
            return null;
        }

        $translation = $formEntity->getTranslation($locale);

        if (!$translation) {
            // No translation for this locale exists
            return null;
        }

        return $formEntity;
    }

Load Form entity.

@param $id
@param $locale

@return Form|null


private function getDefaults(Form $formEntity, $locale)
    {
        // set Defaults
        $defaults = [];

        foreach ($formEntity->getFields() as $field) {
            $fieldTranslation = $field->getTranslation($locale);

            if ($fieldTranslation && $fieldTranslation->getDefaultValue()) {
                $value = $this->formFieldTypePool->get($field->getType())->getDefaultValue($field, $locale);
                $defaults[$field->getKey()] = $value;
            }
        }

        return $defaults;
    }

private
function
getDefaults
(
Form
$
formEntity
,
$
locale
)
{
// set Defaults
$
defaults
=
[
]
;
foreach
(
$
formEntity
->
getFields
(
)
as
$
field
)
{
$
fieldTranslation
=
$
field
->
getTranslation
(
$
locale
)
;
if
(
$
fieldTranslation
&&
$
fieldTranslation
->
getDefaultValue
(
)
)
{
$
value
=
$
this
->
formFieldTypePool
->
get
(
$
field
->
getType
(
)
)
->
getDefaultValue
(
$
field
,
$
locale
)
;
$
defaults
[
$
field
->
getKey
(
)
]
=
$
value
;
}
}
return
$
defaults
;
}

Get defaults.

@param Form $formEntity
@param string $locale

@return array


private function getWebspaceKey()
    {
        $request = $this->requestStack->getCurrentRequest();
        $webspaceKey = null;

        if ($request->get('_sulu')) {
            if ($request->get('_sulu')->getAttribute('webspace')) {
                $webspaceKey = $request->get('_sulu')->getAttribute('webspace')->getKey();
            }
        }

        return $webspaceKey;
    }

private function getWebspaceKey ( ) { $ request = $ this -> requestStack -> getCurrentRequest ( ) ; $ webspaceKey = null ; if ( $ request -> get ( '_sulu' ) ) { if ( $ request -> get ( '_sulu' ) -> getAttribute ( 'webspace' ) ) { $ webspaceKey = $ request -> get ( '_sulu' ) -> getAttribute ( 'webspace' ) -> getKey ( ) ; } } return $ webspaceKey ; }


public function check($checksum, $type, $typeId, $formId, $formName)
    {
        $checksumRaw = $this->createKey($type, $typeId, $formId, $formName);

        return $this->encoder->isPasswordValid($checksum, $checksumRaw, $this->secret);
    }

public function check ( $ checksum , $ type , $ typeId , $ formId , $ formName ) { $ checksumRaw = $ this -> createKey ( $ type , $ typeId , $ formId , $ formName ) ; return $ this -> encoder -> isPasswordValid ( $ checksum , $ checksumRaw , $ this -> secret ) ; }

Check checksum with given parameters.

@param string $checksum
@param string $type
@param string $typeId
@param string $formId
@param string $formName

@return bool


public function get($type, $typeId, $formId, $formName)
    {
        $checksumRaw = $this->createKey($type, $typeId, $formId, $formName);

        return $this->encoder->encodePassword($checksumRaw, $this->secret);
    }

public function get ( $ type , $ typeId , $ formId , $ formName ) { $ checksumRaw = $ this -> createKey ( $ type , $ typeId , $ formId , $ formName ) ; return $ this -> encoder -> encodePassword ( $ checksumRaw , $ this -> secret ) ; }

Create a checksum and encode with secret and given parameters.

@param string $type
@param string $typeId
@param string $formId
@param string $formName

@return string

Create a checksum and encode with secret and given parameters .


public function cgetAction(Request $request)
    {
        /** @var DynamicRepository $repository */
        $repository = $this->get('sulu_form.repository.dynamic');

        $filters = $this->getFilters($request);
        $page = $request->get('page', 1);
        $limit = $request->get('limit');
        $offset = (($page - 1) * $limit);
        $view = $request->get('view', 'default');
        $sortOrder = $request->get('sortOrder', 'asc');
        $sortBy = $request->get('sortBy', 'created');

        $entries = $repository->findByFilters(
            $filters,
            [$sortBy => $sortOrder],
            $limit,
            $offset
        );

        $entries = $this->get('sulu_form.list_builder.dynamic_list_factory')->build($entries, $view);

        // avoid total request when entries < limit
        if (count($entries) == $limit) {
            $total = $repository->countByFilters($filters);
        } else {
            // calculate total
            $total = count($entries) + $offset;
        }

        // create list representation
        $representation = new ListRepresentation(
            $entries,
            'dynamics',
            $request->get('_route'),
            $request->query->all(),
            $page,
            $limit,
            $total
        );

        return $this->handleView($this->view($representation));
    }

Return dynamic form entries.

@param Request $request

@return Response


public function cgetFieldsAction(Request $request)
    {
        $form = $this->loadForm($request);
        $fieldDescriptors = [];

        if ($form) {
            $locale = $this->getLocale($request);
            $fieldDescriptors = $this->get('sulu_form.list_builder.dynamic_list_factory')
                ->getFieldDescriptors($form, $locale);
        }

        return $this->handleView($this->view(array_values($fieldDescriptors)));
    }

Returns the fields for a dynamic form.

@param Request $request

@return Response


public function deleteAction(Request $request, $id)
    {
        $mediaManager = $this->get('sulu_media.media_manager');

        /** @var EntityManagerInterface $entityManager */
        $entityManager = $this->get('doctrine.orm.entity_manager');

        /** @var DynamicRepository $repository */
        $repository = $this->get('sulu_form.repository.dynamic');

        /** @var Dynamic $dynamic */
        $dynamic = $repository->find($id);

        $attachments = array_values($dynamic->getFieldsByType(Dynamic::TYPE_ATTACHMENT));

        foreach ($attachments as $mediaIds) {
            foreach ($mediaIds as $mediaId) {
                if ($mediaId) {
                    try {
                        $mediaManager->delete($mediaId);
                    } catch (MediaNotFoundException $e) {
                        // Do nothing when meida was removed before.
                    }
                }
            }
        }
        $entityManager->remove($dynamic);
        $entityManager->flush();

        return new Response('', 204);
    }

Delete dynamic form entry.

@param Request $request

@return Response


protected function getFilters(Request $request)
    {
        $filters = [
            'type' => $request->get('type'),
            'typeId' => $request->get('typeId'),
            'webspaceKey' => $request->get('webspaceKey'),
            'form' => $request->get('form'),
            'fromDate' => $request->get('fromDate'),
            'toDate' => $request->get('toDate'),
            'search' => $request->get('search'),
            'searchFields' => array_filter(explode(',', $request->get('searchFields', ''))),
        ];

        return array_filter($filters);
    }

protected function getFilters ( Request $ request ) { $ filters = [ 'type' => $ request -> get ( 'type' ) , 'typeId' => $ request -> get ( 'typeId' ) , 'webspaceKey' => $ request -> get ( 'webspaceKey' ) , 'form' => $ request -> get ( 'form' ) , 'fromDate' => $ request -> get ( 'fromDate' ) , 'toDate' => $ request -> get ( 'toDate' ) , 'search' => $ request -> get ( 'search' ) , 'searchFields' => array_filter ( explode ( ',' , $ request -> get ( 'searchFields' , '' ) ) ) , ] ; return array_filter ( $ filters ) ; }

Get filters.

@param Request $request

@return array


protected function loadForm(Request $request)
    {
        $formId = (int) $request->get('form');

        if (!$formId) {
            throw new BadRequestHttpException('"form" is required parameter');
        }

        return $this->get('sulu_form.repository.form')->loadById($formId);
    }

protected
function
loadForm
(
Request
$
request
)
{
$
formId
=
(
int
)
$
request
->
get
(
'form'
)
;
if
(
!
$
formId
)
{
throw
new
BadRequestHttpException
(
'"form" is required parameter'
)
;
}
return
$
this
->
get
(
'sulu_form.repository.form'
)
->
loadById
(
$
formId
)
;
}

Get form.

@param Request $request

@return Form


protected function toString($value)
    {
        if (is_string($value) || is_numeric($value)) {
            return $value;
        }

        if (is_bool($value)) {
            return $value ? 1 : 0;
        }

        if ($value instanceof \DateTime) {
            return $value->format('c');
        }

        if (!$value) {
            return '';
        }

        if (!is_array($value)) {
            throw new \Exception('Invalid value for list builder.');
        }

        return implode($this->delimiter, $value);
    }

protected
function
toString
(
$
value
)
{
if
(
is_string
(
$
value
)
||
is_numeric
(
$
value
)
)
{
return
$
value
;
}
if
(
is_bool
(
$
value
)
)
{
return
$
value
1
:
0
;
}
if
(
$
value
instanceof
\
DateTime
)
{
return
$
value
->
format
(
'c'
)
;
}
if
(
!
$
value
)
{
return
''
;
}
if
(
!
is_array
(
$
value
)
)
{
throw
new
\
Exception
(
'Invalid value for list builder.'
)
;
}
return
implode
(
$
this
->
delimiter
,
$
value
)
;
}

Convert value to string.

@param string|array $value

@return string

@throws \Exception


protected function getMediaUrls($value)
    {
        if (is_string($value)) {
            return $this->getMediaUrl($value);
        }

        if (is_array($value)) {
            foreach ($value as $key => $mediaId) {
                $value[$key] = $this->getMediaUrl($mediaId);
            }

            return implode($this->delimiter, $value);
        }

        return $this->toString($value);
    }

protected function getMediaUrls ( $ value ) { if ( is_string ( $ value ) ) { return $ this -> getMediaUrl ( $ value ) ; } if ( is_array ( $ value ) ) { foreach ( $ value as $ key => $ mediaId ) { $ value [ $ key ] = $ this -> getMediaUrl ( $ mediaId ) ; } return implode ( $ this -> delimiter , $ value ) ; } return $ this -> toString ( $ value ) ; }

Get media urls.

@param string $value

@return string


protected function getDownloadUrl()
    {
        if (null === $this->downloadUrl) {
            $this->downloadUrl = $this->router->generate(
                'sulu_media.website.media.download',
                [
                    'slug' => 'file',
                    'id' => '{id}',
                ],
                true
            );
        }

        return $this->downloadUrl;
    }

protected function getDownloadUrl ( ) { if ( null === $ this -> downloadUrl ) { $ this -> downloadUrl = $ this -> router -> generate ( 'sulu_media.website.media.download' , [ 'slug' => 'file' , 'id' => '{id}' , ] , true ) ; } return $ this -> downloadUrl ; }

For performance generate route only once.

@return string

For performance generate route only once .


protected function getChoices(FormFieldTranslation $translation)
    {
        $choices = preg_split('/\r\n|\r|\n/', $translation->getOption('choices'), -1, PREG_SPLIT_NO_EMPTY);

        return array_combine($choices, $choices);
    }

protected function getChoices ( FormFieldTranslation $ translation ) { $ choices = preg_split ( '/\r\n|\r|\n/' , $ translation -> getOption ( 'choices' ) , - 1 , PREG_SPLIT_NO_EMPTY ) ; return array_combine ( $ choices , $ choices ) ; }

Get choices.

@param FormFieldTranslation $translation

@return array


private function getChoiceOptions(
        FormFieldTranslation $translation,
        $options
    ) {
        if (isset($options['attr']['placeholder'])) {
            $options['placeholder'] = $options['attr']['placeholder'];
            unset($options['attr']['placeholder']);
        }

        // Choices.
        $choices = $this->getChoices($translation);
        $options['choices_as_values'] = true;
        $options['choices'] = $choices;

        return $options;
    }

private
function
getChoiceOptions
(
FormFieldTranslation
$
translation
,
$
options
)
{
if
(
isset
(
$
options
[
'attr'
]
[
'placeholder'
]
)
)
{
$
options
[
'placeholder'
]
=
$
options
[
'attr'
]
[
'placeholder'
]
;
unset
(
$
options
[
'attr'
]
[
'placeholder'
]
)
;
}
// Choices.
$
choices
=
$
this
->
getChoices
(
$
translation
)
;
$
options
[
'choices_as_values'
]
=
true
;
$
options
[
'choices'
]
=
$
choices
;
return
$
options
;
}

Returns options for multichoice form type like select, multiple select, radio or checkboxes.

@param FormFieldTranslation $translation
@param array $options

@return array

Returns options for multichoice form type like select multiple select radio or checkboxes .


public function getFormById($id, $type, $typeId, $locale = null, $name = 'form')
    {
        $form = $this->formBuilder->build((int) $id, $type, $typeId, $locale, $name);

        if (!$form) {
            return;
        }

        return $form->createView();
    }

public function getFormById ( $ id , $ type , $ typeId , $ locale = null , $ name = 'form' ) { $ form = $ this -> formBuilder -> build ( ( int ) $ id , $ type , $ typeId , $ locale , $ name ) ; if ( ! $ form ) { return ; } return $ form -> createView ( ) ; }

Returns FormView by given params.

@param int $id
@param string $type
@param string $typeId
@param mixed $locale
@param string $name

@return FormView


public function onKernelRequest(GetResponseEvent $event)
    {
        if (!$event->isMasterRequest()) {
            // do nothing if it's not the master request
            return;
        }

        $request = $event->getRequest();

        if (!$request->isMethod('post')) {
            // do nothing if it's not a post request
            return;
        }

        try {
            /** @var FormInterface $form */
            $form = $this->formBuilder->buildByRequest($request);

            if (!$form || !$form->isSubmitted() || !$form->isValid()) {
                // do nothing when no form was found or not valid
                return;
            }
        } catch (\Exception $e) {
            // Catch all exception on build form by request
            return;
        }

        /** @var Dynamic $dynamic */
        $dynamic = $form->getData();
        $configuration = $this->formConfigurationFactory->buildByDynamic($dynamic);
        $dynamic->setLocale($request->getLocale()); // Need to be set to request locale for shadow pages, configuraiton will hold the original locale

        if ($this->formHandler->handle($form, $configuration)) {
            $serializedObject = $dynamic->getForm()->serializeForLocale($dynamic->getLocale(), $dynamic);
            $dynFormSavedEvent = new DynFormSavedEvent($serializedObject, $dynamic);
            $this->eventDispatcher->dispatch(DynFormSavedEvent::NAME, $dynFormSavedEvent);

            $response = new RedirectResponse('?send=true');
            $event->setResponse($response);
        }
    }

On Kernel request.

@param GetResponseEvent $event


public function getTranslation($locale, $create = false, $fallback = false)
    {
        foreach ($this->translations as $translation) {
            if ($translation->getLocale() == $locale) {
                return $translation;
            }
        }

        if ($create) {
            $translation = new FormTranslation();
            $translation->setLocale($locale);

            return $translation;
        }

        if ($fallback) {
            return $this->getTranslation($this->getDefaultLocale());
        }

        return;
    }

public function getTranslation ( $ locale , $ create = false , $ fallback = false ) { foreach ( $ this -> translations as $ translation ) { if ( $ translation -> getLocale ( ) == $ locale ) { return $ translation ; } } if ( $ create ) { $ translation = new FormTranslation ( ) ; $ translation -> setLocale ( $ locale ) ; return $ translation ; } if ( $ fallback ) { return $ this -> getTranslation ( $ this -> getDefaultLocale ( ) ) ; } return ; }

Get translation.

@param string $locale
@param bool $create
@param bool $fallback

@return FormTranslation|null


public function getField($key)
    {
        foreach ($this->fields as $field) {
            if ($field->getKey() == $key) {
                return $field;
            }
        }
    }

public function getField ( $ key ) { foreach ( $ this -> fields as $ field ) { if ( $ field -> getKey ( ) == $ key ) { return $ field ; } } }

Get field by key.

@param string $key

@return FormField|null


public function getFieldsNotInArray($keys)
    {
        $fields = [];

        foreach ($this->fields as $field) {
            if (!in_array($field->getKey(), $keys)) {
                $fields[] = $field;
            }
        }

        return $fields;
    }

public function getFieldsNotInArray ( $ keys ) { $ fields = [ ] ; foreach ( $ this -> fields as $ field ) { if ( ! in_array ( $ field -> getKey ( ) , $ keys ) ) { $ fields [ ] = $ field ; } } return $ fields ; }

Get fields not in array.

@param $keys

@return FormField[]


public function serializeForLocale($locale, Dynamic $dynamic = null)
    {
        $fields = [];

        foreach ($this->fields as $field) {
            $fieldTranslation = $field->getTranslation($locale, false, true);
            $value = null;

            if ($dynamic) {
                $value = $dynamic->{$field->getKey()};
            }

            $fields[$field->getOrder()] = [
                'key' => $field->getKey(),
                'type' => $field->getType(),
                'title' => $fieldTranslation->getTitle(),
                'options' => $fieldTranslation->getOptions(),
                'defaultValue' => $fieldTranslation->getDefaultValue(),
                'placeholder' => $fieldTranslation->getPlaceholder(),
                'shortTitle' => $fieldTranslation->getShortTitle(),
                'value' => $value,
            ];

            ksort($fields);
        }

        $translation = $this->getTranslation($locale, false, true);

        return [
            'id' => $dynamic ? $dynamic->getId() : null,
            'formId' => $this->getId(),
            'title' => $translation->getTitle(),
            'subject' => $translation->getSubject(),
            'mailText' => $translation->getMailText(),
            'submitLabel' => $translation->getSubmitLabel(),
            'successText' => $translation->getSuccessText(),
            'fromEmail' => $translation->getFromEmail(),
            'fromName' => $translation->getFromName(),
            'toEmail' => $translation->getToEmail(),
            'toName' => $translation->getToName(),
            'fields' => $fields,
            'created' => $dynamic ? $dynamic->getCreated() : null,
        ];
    }

public function serializeForLocale ( $ locale , Dynamic $ dynamic = null ) { $ fields = [ ] ; foreach ( $ this -> fields as $ field ) { $ fieldTranslation = $ field -> getTranslation ( $ locale , false , true ) ; $ value = null ; if ( $ dynamic ) { $ value = $ dynamic -> { $ field -> getKey ( ) } ; } $ fields [ $ field -> getOrder ( ) ] = [ 'key' => $ field -> getKey ( ) , 'type' => $ field -> getType ( ) , 'title' => $ fieldTranslation -> getTitle ( ) , 'options' => $ fieldTranslation -> getOptions ( ) , 'defaultValue' => $ fieldTranslation -> getDefaultValue ( ) , 'placeholder' => $ fieldTranslation -> getPlaceholder ( ) , 'shortTitle' => $ fieldTranslation -> getShortTitle ( ) , 'value' => $ value , ] ; ksort ( $ fields ) ; } $ translation = $ this -> getTranslation ( $ locale , false , true ) ; return [ 'id' => $ dynamic ? $ dynamic -> getId ( ) : null , 'formId' => $ this -> getId ( ) , 'title' => $ translation -> getTitle ( ) , 'subject' => $ translation -> getSubject ( ) , 'mailText' => $ translation -> getMailText ( ) , 'submitLabel' => $ translation -> getSubmitLabel ( ) , 'successText' => $ translation -> getSuccessText ( ) , 'fromEmail' => $ translation -> getFromEmail ( ) , 'fromName' => $ translation -> getFromName ( ) , 'toEmail' => $ translation -> getToEmail ( ) , 'toName' => $ translation -> getToName ( ) , 'fields' => $ fields , 'created' => $ dynamic ? $ dynamic -> getCreated ( ) : null , ] ; }

Return a localized array of the object.

@param $locale
@param Dynamic $dynamic

@return array

Return a localized array of the object .


public function formAction(StructureInterface $structure, $preview = false, $partial = false)
    {
        /** @var Request $request */
        $request = $this->get('request_stack')->getCurrentRequest();

        // get attributes
        $attributes = $this->getAttributes([], $structure, $preview);

        $template = $structure->getKey();

        $typeClass = $this->getTypeClass($template);
        /** @var AbstractType $type */
        $type = $this->get('form.registry')->getType($typeClass)->getInnerType();
        $type->setAttributes($attributes);

        $this->form = $this->get('form.factory')->create($typeClass);
        $this->form->handleRequest($request);

        if ($this->form->isSubmitted()
            && $this->form->isValid()
            && $response = $this->handleFormSubmit($request, $type, $attributes)
        ) {
            // success form submit

            return $response;
        }

        return parent::indexAction($structure, $preview, $partial);
    }

public
function
formAction
(
StructureInterface
$
structure
,
$
preview
=
false
,
$
partial
=
false
)
{
/** @var Request $request */
$
request
=
$
this
->
get
(
'request_stack'
)
->
getCurrentRequest
(
)
;
// get attributes
$
attributes
=
$
this
->
getAttributes
(
[
]
,
$
structure
,
$
preview
)
;
$
template
=
$
structure
->
getKey
(
)
;
$
typeClass
=
$
this
->
getTypeClass
(
$
template
)
;
/** @var AbstractType $type */
$
type
=
$
this
->
get
(
'form.registry'
)
->
getType
(
$
typeClass
)
->
getInnerType
(
)
;
$
type
->
setAttributes
(
$
attributes
)
;
$
this
->
form
=
$
this
->
get
(
'form.factory'
)
->
create
(
$
typeClass
)
;
$
this
->
form
->
handleRequest
(
$
request
)
;
if
(
$
this
->
form
->
isSubmitted
(
)
&&
$
this
->
form
->
isValid
(
)
&&
$
response
=
$
this
->
handleFormSubmit
(
$
request
,
$
type
,
$
attributes
)
)
{
// success form submit
return
$
response
;
}
return
parent
::
indexAction
(
$
structure
,
$
preview
,
$
partial
)
;
}

Form action.

@param StructureInterface $structure
@param bool $preview
@param bool $partial

@return JsonResponse|RedirectResponse|Response


public function onlyAction(Request $request, $key)
    {
        $ajaxTemplates = $this->container->getParameter('sulu_form.ajax_templates');

        if (!$ajaxTemplates[$key]) {
            throw new NotFoundHttpException();
        }

        $typeClass = $this->getTypeClass($key);
        /** @var AbstractType $type */
        $type = $this->get('form.registry')->getType($typeClass)->getInnerType();
        $this->form = $this->get('form.factory')->create($typeClass);
        $this->form->handleRequest($request);

        if ($this->form->isSubmitted()
            && $this->form->isValid()
            && $response = $this->handleFormOnlySubmit($request, $type)
        ) {
            // success form submit

            return $response;
        }

        return $this->render($ajaxTemplates[$key], ['form' => $this->form->createView()]);
    }

public
function
onlyAction
(
Request
$
request
,
$
key
)
{
$
ajaxTemplates
=
$
this
->
container
->
getParameter
(
'sulu_form.ajax_templates'
)
;
if
(
!
$
ajaxTemplates
[
$
key
]
)
{
throw
new
NotFoundHttpException
(
)
;
}
$
typeClass
=
$
this
->
getTypeClass
(
$
key
)
;
/** @var AbstractType $type */
$
type
=
$
this
->
get
(
'form.registry'
)
->
getType
(
$
typeClass
)
->
getInnerType
(
)
;
$
this
->
form
=
$
this
->
get
(
'form.factory'
)
->
create
(
$
typeClass
)
;
$
this
->
form
->
handleRequest
(
$
request
)
;
if
(
$
this
->
form
->
isSubmitted
(
)
&&
$
this
->
form
->
isValid
(
)
&&
$
response
=
$
this
->
handleFormOnlySubmit
(
$
request
,
$
type
)
)
{
// success form submit
return
$
response
;
}
return
$
this
->
render
(
$
ajaxTemplates
[
$
key
]
,
[
'form'
=>
$
this
->
form
->
createView
(
)
]
)
;
}

Form only action.

@param Request $request
@param string $key

@return RedirectResponse|Response

@throws NotFoundHttpException


private function handleFormSubmit(Request $request, $type, $attributes)
    {
        // handle form submit
        $configuration = $this->get('sulu_form.configuration.form_configuration_factory')->buildByType(
            $type,
            $this->form->getData(),
            $request->getLocale(),
            $attributes
        );

        $success = $this->get('sulu_form.handler')->handle($this->form, $configuration);

        if ($success) {
            if ($request->isXmlHttpRequest()) {
                return new JsonResponse(['send' => $success]);
            }

            return new RedirectResponse('?send=true');
        }

        if ($request->isXmlHttpRequest()) {
            return new JsonResponse(
                [
                    'send' => false,
                    'errors' => $this->getErrors(),
                ],
                400
            );
        }
    }

Handle form submit.

@param Request $request
@param AbstractType $type
@param array $attributes

@return JsonResponse|RedirectResponse


private function handleFormOnlySubmit(Request $request, $type)
    {
        // handle form submit
        $configuration = $this->get('sulu_form.configuration.form_configuration_factory')->buildByType(
            $type,
            $this->form->getData(),
            $request->getLocale(),
            []
        );

        if ($this->get('sulu_form.handler')->handle($this->form, $configuration)) {
            return new RedirectResponse('?send=true');
        }
    }

Handle form only submit.

@param Request $request
@param AbstractType $type

@return RedirectResponse


public function tokenAction(Request $request)
    {
        $formName = $request->get('form');
        $csrfToken = $this->get('security.csrf.token_manager')->getToken(
            $request->get('form')
        )->getValue();

        $content = $csrfToken;

        // this should be the default behaviour in future because for varnish its needed
        if ($request->get('html')) {
            $content = sprintf(
                '<input type="hidden" id="%s__token" name="%s[_token]" value="%s" />',
                $formName,
                $formName,
                $csrfToken
            );
        }

        $response = new Response($content);

        /* Deactivate Cache for this token action */
        $response->setSharedMaxAge(0);
        $response->setMaxAge(0);
        // set shared will set the request to public so it need to be done after shared max set to 0
        $response->setPrivate();
        $response->headers->addCacheControlDirective('no-cache', true);
        $response->headers->addCacheControlDirective('must-revalidate', true);
        $response->headers->addCacheControlDirective('no-store', true);

        return $response;
    }

Generates a token for the form.

@param Request $request

@return Response


protected function getErrors()
    {
        $errors = [];

        $generalErrors = [];
        foreach ($this->form->getErrors() as $error) {
            $generalErrors[] = $error->getMessage();
        }

        if (!empty($generalErrors)) {
            $errors['general'] = $generalErrors;
        }

        foreach ($this->form->all() as $field) {
            $fieldErrors = [];

            foreach ($field->getErrors() as $error) {
                $fieldErrors[] = $error->getMessage();
            }

            if (!empty($fieldErrors)) {
                $errors[$field->getName()] = $fieldErrors;
            }
        }

        return $errors;
    }

protected function getErrors ( ) { $ errors = [ ] ; $ generalErrors = [ ] ; foreach ( $ this -> form -> getErrors ( ) as $ error ) { $ generalErrors [ ] = $ error -> getMessage ( ) ; } if ( ! empty ( $ generalErrors ) ) { $ errors [ 'general' ] = $ generalErrors ; } foreach ( $ this -> form -> all ( ) as $ field ) { $ fieldErrors = [ ] ; foreach ( $ field -> getErrors ( ) as $ error ) { $ fieldErrors [ ] = $ error -> getMessage ( ) ; } if ( ! empty ( $ fieldErrors ) ) { $ errors [ $ field -> getName ( ) ] = $ fieldErrors ; } } return $ errors ; }


public function handle(FormInterface $form, FormConfigurationInterface $configuration)
    {
        if (!$form->isValid()) {
            return false;
        }

        $mediaIds = $this->uploadMedia($form, $configuration);
        $this->mapMediaIds($form->getData(), $mediaIds);
        $this->save($form, $configuration);
        $this->sendMails($form, $configuration);

        return true;
    }

public function handle ( FormInterface $ form , FormConfigurationInterface $ configuration ) { if ( ! $ form -> isValid ( ) ) { return false ; } $ mediaIds = $ this -> uploadMedia ( $ form , $ configuration ) ; $ this -> mapMediaIds ( $ form -> getData ( ) , $ mediaIds ) ; $ this -> save ( $ form , $ configuration ) ; $ this -> sendMails ( $ form , $ configuration ) ; return true ; }

Handle form.

@param FormInterface $form
@param FormConfigurationInterface $configuration

@return bool


private function save(FormInterface $form, FormConfigurationInterface $configuration)
    {
        $this->eventDispatcher->dispatch(
            self::EVENT_FORM_SAVE,
            new FormEvent(
                $form,
                $configuration
            )
        );

        if (!$configuration->getSave()) {
            return;
        }

        $this->entityManager->persist($form->getData());
        $this->entityManager->flush();

        $this->eventDispatcher->dispatch(
            self::EVENT_FORM_SAVED,
            new FormEvent(
                $form,
                $configuration
            )
        );
    }

private function save ( FormInterface $ form , FormConfigurationInterface $ configuration ) { $ this -> eventDispatcher -> dispatch ( self :: EVENT_FORM_SAVE , new FormEvent ( $ form , $ configuration ) ) ; if ( ! $ configuration -> getSave ( ) ) { return ; } $ this -> entityManager -> persist ( $ form -> getData ( ) ) ; $ this -> entityManager -> flush ( ) ; $ this -> eventDispatcher -> dispatch ( self :: EVENT_FORM_SAVED , new FormEvent ( $ form , $ configuration ) ) ; }

Save form.

@param FormInterface $form
@param FormConfigurationInterface $configuration


private function uploadMedia(FormInterface $form, FormConfigurationInterface $configuration)
    {
        $this->attachments = [];
        $mediaIds = [];

        foreach ($configuration->getFileFields() as $field => $collectionId) {
            if (!$form->has($field) || !count($form[$field]->getData())) {
                continue;
            }

            $files = $form[$field]->getData();
            $ids = [];

            if (!is_array($files)) {
                $files = [$files];
            }

            /** @var UploadedFile $file */
            foreach ($files as $file) {
                if (!$file instanceof UploadedFile) {
                    continue;
                }

                $media = $this->mediaManager->save(
                    $file,
                    $this->getMediaData($file, $form, $configuration, $collectionId),
                    null
                );

                // save attachments data for swift message
                $this->attachments[] = $file;
                $ids[] = $media->getId();
            }

            $mediaIds[$field] = $ids;
        }

        return $mediaIds;
    }

Upload media.

@param FormInterface $form
@param FormConfigurationInterface $configuration

@return array


private function mapMediaIds($entity, $mediaIds)
    {
        $accessor = new PropertyAccessor();

        foreach ($mediaIds as $key => $value) {
            $accessor->setValue($entity, $key, $value);
        }

        return $entity;
    }

private function mapMediaIds ( $ entity , $ mediaIds ) { $ accessor = new PropertyAccessor ( ) ; foreach ( $ mediaIds as $ key => $ value ) { $ accessor -> setValue ( $ entity , $ key , $ value ) ; } return $ entity ; }

Map media ids.

@param mixed $entity
@param int[] $mediaIds

@return mixed


protected function getMediaData(
        UploadedFile $file,
        FormInterface $form,
        FormConfigurationInterface $configuration,
        $collectionId
    ) {
        return [
            'collection' => $collectionId,
            'locale' => $configuration->getLocale(),
            'title' => $file->getClientOriginalName(),
        ];
    }

protected function getMediaData ( UploadedFile $ file , FormInterface $ form , FormConfigurationInterface $ configuration , $ collectionId ) { return [ 'collection' => $ collectionId , 'locale' => $ configuration -> getLocale ( ) , 'title' => $ file -> getClientOriginalName ( ) , ] ; }

Get media data.

@param UploadedFile $file
@param FormInterface $form
@param FormConfigurationInterface $configuration
@param int $collectionId

@return array


private function getMailChimpLists()
    {
        $lists = [];

        // If Milchimp class doesn't exist or no key is set return empty list.
        if (!class_exists(\DrewM\MailChimp\MailChimp::class) || !$this->apiKey) {
            return $lists;
        }

        $mailChimp = new \DrewM\MailChimp\MailChimp($this->apiKey);
        $response = $mailChimp->get('lists', ['count' => 100]);

        if (!isset($response['lists'])) {
            return $lists;
        }

        foreach ($response['lists'] as $list) {
            $lists[] = [
                'id' => $list['id'],
                'name' => $list['name'],
            ];
        }

        return $lists;
    }

Returns array of Mailchimp lists of given account defined by the API key.

@return array

Returns array of Mailchimp lists of given account defined by the API key .


protected function getBuilder($alias = null)
    {
        if (!$alias || 'default' === $alias) {
            $alias = $this->defaultBuilder;
        }

        if (!$this->builders[$alias]) {
            throw new \Exception(sprintf('Bilder with the name "%s" not found.', $alias));
        }

        return $this->builders[$alias];
    }

protected
function
getBuilder
(
$
alias
=
)
{
if
(
!
$
alias
||
'default'
===
$
alias
)
{
$
alias
=
$
this
->
defaultBuilder
;
}
if
(
!
$
this
->
builders
[
$
alias
]
)
{
throw
new
\
Exception
(
sprintf
(
'Bilder with the name "%s" not found.'
,
$
alias
)
)
;
}
return
$
this
->
builders
[
$
alias
]
;
}

Get builder.

@param string $alias

@return DynamicListBuilderInterface

@throws \Exception


public function getBlockPrefix()
    {
        $fqcn = get_class($this);
        $name = $this->getName();
        // For BC: Use the name as block prefix if one is set
        return $name !== $fqcn ? $name : StringUtil::fqcnToBlockPrefix($fqcn);
    }

Returns the prefix of the template block name for this type.

The block prefixes default to the underscored short class name with
the "Type" suffix removed (e.g. "UserProfileType" => "user_profile").

@see https://github.com/symfony/symfony/blob/2.8/src/Symfony/Component/Form/AbstractType.php

@return string The prefix of the template block name

Returns the prefix of the template block name for this type .


private function createCollection($title, $parentId, $collectionKey, $locale)
    {
        $parentCollection = $this->collectionManager->save([
            'title' => $title,
            'type' => ['id' => 2],
            'parent' => $parentId,
            'key' => $collectionKey,
            'locale' => $locale,
        ], null);

        return $parentCollection->getId();
    }

private function createCollection ( $ title , $ parentId , $ collectionKey , $ locale ) { $ parentCollection = $ this -> collectionManager -> save ( [ 'title' => $ title , 'type' => [ 'id' => 2 ] , 'parent' => $ parentId , 'key' => $ collectionKey , 'locale' => $ locale , ] , null ) ; return $ parentCollection -> getId ( ) ; }

Create collection.

@param string $title
@param int $parentId
@param string $collectionKey
@param string $locale

@return int


private function loadCollectionId(
        $collectionKey,
        $locale
    ) {
        try {
            $collection = $this->collectionManager->getByKey($collectionKey, $locale);

            if (!$collection) {
                return;
            }

            return $collection->getId();
        } catch (\Exception $e) {
            // Catch all exception
        }
    }

private
function
loadCollectionId
(
$
collectionKey
,
$
locale
)
{
try
{
$
collection
=
$
this
->
collectionManager
->
getByKey
(
$
collectionKey
,
$
locale
)
;
if
(
!
$
collection
)
{
return
;
}
return
$
collection
->
getId
(
)
;
}
catch
(
\
Exception
$
e
)
{
// Catch all exception
}
}

Load collection id.

@param string $collectionKey
@param string $locale

@return int


private function getItemWidthNumber($width)
    {
        switch ($width) {
            case 'one-sixth':
                $itemWidth = 2;
                break;
            case 'five-sixths':
                $itemWidth = 10;
                break;
            case 'one-quarter':
                $itemWidth = 3;
                break;
            case 'three-quarters':
                $itemWidth = 9;
                break;
            case 'one-third':
                $itemWidth = 4;
                break;
            case 'two-thirds':
                $itemWidth = 8;
                break;
            case 'half':
                $itemWidth = 6;
                break;
            case 'full':
                $itemWidth = 12;
                break;
            default:
                $itemWidth = 12;
        }

        return $itemWidth;
    }

private function getItemWidthNumber ( $ width ) { switch ( $ width ) { case 'one-sixth' : $ itemWidth = 2 ; break ; case 'five-sixths' : $ itemWidth = 10 ; break ; case 'one-quarter' : $ itemWidth = 3 ; break ; case 'three-quarters' : $ itemWidth = 9 ; break ; case 'one-third' : $ itemWidth = 4 ; break ; case 'two-thirds' : $ itemWidth = 8 ; break ; case 'half' : $ itemWidth = 6 ; break ; case 'full' : $ itemWidth = 12 ; break ; default : $ itemWidth = 12 ; } return $ itemWidth ; }

Get item width number.

@param string $width

@return int


private function getLastWidth(&$currentWidthValue, $width, $nextWidth)
    {
        $widthNumber = $this->getItemWidthNumber($width);
        $nextWidthNumber = $this->getItemWidthNumber($nextWidth);

        $currentWidthValue += $widthNumber;

        if (0 == $currentWidthValue % 12) {
            return true;
        }

        // if next item has no space in current row the current item is last
        if (($currentWidthValue % 12) + $nextWidthNumber > 12) {
            $currentWidthValue += 12 - $currentWidthValue % 12;

            return true;
        }

        return false;
    }

Get last width.

@param int $currentWidthValue
@param string $width
@param string $nextWidth

@return bool


public static function rethrow(PDOException $e) {
		// the 2-character class of the error (if any) has the highest priority
		$errorClass = null;
		// the 3-character subclass of the error (if any) has a medium priority
		$errorSubClass = null;
		// the full error code itself has the lowest priority
		$error = null;

		// if an error code is available
		if (!empty($e->getCode())) {
			// remember the error code
			$error = $e->getCode();

			// if the error code is an "SQLSTATE" error
			if (strlen($e->getCode()) === 5) {
				// remember the class as well
				$errorClass = substr($e->getCode(), 0, 2);
				// and remember the subclass
				$errorSubClass = substr($e->getCode(), 2);
			}
		}

		if ($errorClass === '3D') {
			throw new NoDatabaseSelectedError($e->getMessage());
		}
		elseif ($errorClass === '23') {
			throw new IntegrityConstraintViolationException($e->getMessage());
		}
		elseif ($errorClass === '42') {
			if ($errorSubClass === 'S02') {
				throw new TableNotFoundError($e->getMessage());
			}
			elseif ($errorSubClass === 'S22') {
				throw new UnknownColumnError($e->getMessage());
			}
			else {
				throw new SyntaxError($e->getMessage());
			}
		}
		else {
			if ($error === 1044) {
				throw new WrongCredentialsError($e->getMessage());
			}
			elseif ($error === 1049) {
				throw new DatabaseNotFoundError($e->getMessage());
			}
			else {
				throw new Error($e->getMessage());
			}
		}
	}

Handles the specified exception thrown by PDO and tries to throw a more specific exception or error instead

@param PDOException $e the exception thrown by PDO
@throws Exception
@throws Error


public function setHostname($hostname = null) {
		$this->hostname = $hostname !== null ? (string) $hostname : null;

		return $this;
	}

public function setHostname ( $ hostname = null ) { $ this -> hostname = $ hostname !== null ? ( string ) $ hostname : null ; return $ this ; }

Sets the hostname

@param string|null $hostname the hostname where the database can be accessed, e.g. `db.example.com`
@return static this instance for chaining


public function setUnixSocket($unixSocket = null) {
		$this->unixSocket = $unixSocket !== null ? (string) $unixSocket : null;

		return $this;
	}

public function setUnixSocket ( $ unixSocket = null ) { $ this -> unixSocket = $ unixSocket !== null ? ( string ) $ unixSocket : null ; return $ this ; }

Sets the unix socket

@param string|null $unixSocket the UNIX socket to use, e.g. `/tmp/db.sock`
@return static this instance for chaining


public function setMemory($memory = null) {
		$this->memory = $memory !== null ? (bool) $memory : null;

		return $this;
	}

public function setMemory ( $ memory = null ) { $ this -> memory = $ memory !== null ? ( bool ) $ memory : null ; return $ this ; }

Sets whether to keep the database in memory only

@param bool|null $memory whether to keep the database in memory only
@return static this instance for chaining


public function setFilePath($filePath = null) {
		$this->filePath = $filePath !== null ? (string) $filePath : null;

		return $this;
	}

public function setFilePath ( $ filePath = null ) { $ this -> filePath = $ filePath !== null ? ( string ) $ filePath : null ; return $ this ; }

Sets the file path

@param string|null $filePath the path to the file where the database can be accessed on disk, e.g. `/opt/databases/mydb.ext`
@return static this instance for chaining


public function setDatabaseName($databaseName = null) {
		$this->databaseName = $databaseName !== null ? (string) $databaseName : null;

		return $this;
	}

public function setDatabaseName ( $ databaseName = null ) { $ this -> databaseName = $ databaseName !== null ? ( string ) $ databaseName : null ; return $ this ; }

Sets the database name

@param string|null $databaseName the name of the database, e.g. `my_application`
@return static this instance for chaining


public function setCharset($charset = null) {
		$this->charset = $charset !== null ? (string) $charset : null;

		return $this;
	}

public function setCharset ( $ charset = null ) { $ this -> charset = $ charset !== null ? ( string ) $ charset : null ; return $ this ; }

Sets the charset

@param string|null $charset the character encoding, e.g. `utf8`
@return static this instance for chaining


private function ensureConnected() {
		if ($this->pdo === null) {
			try {
				$this->pdo = new PDO($this->dsn->getDsn(), $this->dsn->getUsername(), $this->dsn->getPassword());
			}
			catch (PDOException $e) {
				ErrorHandler::rethrow($e);
			}

			// iterate over all listeners waiting for the connection to be established
			foreach ($this->onConnectListeners as $onConnectListener) {
				// execute the callback
				$onConnectListener($this);
			}

			// discard the listeners now that they have all been executed
			$this->onConnectListeners = [];

			$this->dsn = null;
		}

		if ($this->driverName === null) {
			$this->driverName = $this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
		}
	}

Makes sure that the connection is active and otherwise establishes it automatically


private function configureConnection(array &$newAttributes = null, array &$oldAttributes = null) {
		// if a connection is available
		if (isset($this->pdo)) {
			// if there are attributes that need to be applied
			if (isset($newAttributes)) {
				// get the keys and values of the attributes to apply
				foreach ($newAttributes as $key => $newValue) {
					// if the old state of the connection must be preserved
					if (isset($oldAttributes)) {
						// retrieve the old value for this attribute
						try {
							$oldValue = @$this->pdo->getAttribute($key);
						}
						catch (PDOException $e) {
							// the specified attribute is not supported by the driver
							$oldValue = null;
						}

						// if an old value has been found
						if (isset($oldValue)) {
							// if the old value differs from the new value that we're going to set
							if ($oldValue !== $newValue) {
								// save the old value so that we're able to restore it later
								$oldAttributes[$key] = $oldValue;
							}
						}
					}

					// and then set the desired new value
					$this->pdo->setAttribute($key, $newValue);
				}

				// if the old state of the connection doesn't need to be preserved
				if (!isset($oldAttributes)) {
					// we're done updating attributes for this connection once and for all
					$newAttributes = null;
				}
			}
		}
	}

Configures this connection by setting appropriate attributes

@param array|null $newAttributes the new attributes to set
@param array|null $oldAttributes where old configurations may be saved to restore them later


private function selectInternal(callable $callback, $query, array $bindValues = null) {
		$this->normalizeConnection();

		try {
			// create a prepared statement from the supplied SQL string
			$stmt = $this->pdo->prepare($query);
		}
		catch (PDOException $e) {
			ErrorHandler::rethrow($e);
		}

		// if a performance profiler has been defined
		if (isset($this->profiler)) {
			$this->profiler->beginMeasurement();
		}

		/** @var PDOStatement $stmt */

		// bind the supplied values to the query and execute it
		try {
			$stmt->execute($bindValues);
		}
		catch (PDOException $e) {
			ErrorHandler::rethrow($e);
		}

		// if a performance profiler has been defined
		if (isset($this->profiler)) {
			$this->profiler->endMeasurement($query, $bindValues, 1);
		}

		// fetch the desired results from the result set via the supplied callback
		$results = $callback($stmt);

		$this->denormalizeConnection();

		// if the result is empty
		if (empty($results) && $stmt->rowCount() === 0) {
			// consistently return `null`
			return null;
		}
		// if some results have been found
		else {
			// return these as extracted by the callback
			return $results;
		}
	}

Selects from the database using the specified query and returns what the supplied callback extracts from the result set

You should not include any dynamic input in the query

Instead, pass `?` characters (without any quotes) as placeholders and pass the actual values in the third argument

@param callable $callback the callback that receives the executed statement and can then extract and return the desired results
@param string $query the query to select with
@param array|null $bindValues (optional) the values to bind as replacements for the `?` characters in the query
@return mixed whatever the callback has extracted and returned from the result set


public function getQueues($previous = null, $per_page = self::LIST_QUEUES_PER_PAGE)
    {
        $url = "projects/{$this->project_id}/queues";
        $params = array();
        if (!is_null($previous)) {
            $params['previous'] = $previous;
        }
        if ($per_page !== self::LIST_QUEUES_PER_PAGE) {
            $params['per_page'] = (int) $per_page;
        }
        $this->setJsonHeaders();
        return self::json_decode($this->apiCall(self::GET, $url, $params))->queues;
    }

public function getQueues ( $ previous = null , $ per_page = self :: LIST_QUEUES_PER_PAGE ) { $ url = "projects/{$this->project_id}/queues" ; $ params = array ( ) ; if ( ! is_null ( $ previous ) ) { $ params [ 'previous' ] = $ previous ; } if ( $ per_page !== self :: LIST_QUEUES_PER_PAGE ) { $ params [ 'per_page' ] = ( int ) $ per_page ; } $ this -> setJsonHeaders ( ) ; return self :: json_decode ( $ this -> apiCall ( self :: GET , $ url , $ params ) ) -> queues ; }

Get list of message queues

@param int $previous
Zero-indexed page to view
@param int $per_page
Number of queues per page


public function getQueue($queue_name)
    {
        $queue = rawurlencode($queue_name);
        $url = "projects/{$this->project_id}/queues/$queue";
        $this->setJsonHeaders();
        return self::json_decode($this->apiCall(self::GET, $url))->queue;
    }

Get information about queue.
Also returns queue size.

@param string $queue_name
@return mixed

Get information about queue . Also returns queue size .


public function postMessage($queue_name, $message, $properties = array())
    {
        $msg = new IronMQMessage($message, $properties);
        $req = array(
            "messages" => array($msg->asArray()),
        );
        $this->setJsonHeaders();
        $queue = rawurlencode($queue_name);
        $url = "projects/{$this->project_id}/queues/$queue/messages";
        $res = $this->apiCall(self::POST, $url, $req);
        $decoded = self::json_decode($res);
        $decoded->id = $decoded->ids[0];
        return $decoded;
    }

Push a message on the queue

Examples:

$ironmq->postMessage("test_queue", "Hello world");

$ironmq->postMessage("test_queue", "Test Message", array(
'timeout' => 120,
'delay' => 2,
'expires_in' => 2*24*3600 # 2 days
));

@param string $queue_name Name of the queue.
@param string $message
@param array $properties
@return mixed


public function postMessages($queue_name, $messages, $properties = array())
    {
        $req = array(
            "messages" => array(),
        );
        foreach ($messages as $message) {
            $msg = new IronMQMessage($message, $properties);
            array_push($req['messages'], $msg->asArray());
        }
        $this->setJsonHeaders();
        $queue = rawurlencode($queue_name);
        $url = "projects/{$this->project_id}/queues/$queue/messages";
        $res = $this->apiCall(self::POST, $url, $req);
        return self::json_decode($res);
    }

Push multiple messages on the queue

Example:
<code>
$ironmq->postMessages("test_queue", array("Lorem", "Ipsum"), array(
'timeout' => 120,
'delay' => 2,
'expires_in' => 2*24*3600 # 2 days
));
</code>

@param string $queue_name Name of the queue.
@param array $messages array of messages, each message same as for postMessage() method
@param array $properties array of message properties, applied to each message in $messages
@return mixed


public function getMessageById($queue_name, $message_id)
    {
        $this->setJsonHeaders();
        $queue = rawurlencode($queue_name);
        $url = "projects/{$this->project_id}/queues/$queue/messages/{$message_id}";
        return self::json_decode($this->apiCall(self::GET, $url))->message;
    }

Get the message with the given id.
@param string $queue_name Queue name
@param string $message_id Message ID
@return mixed


public function touchMessage($queue_name, $message_id, $reservation_id, $timeout)
    {
        $req = array(
            "reservation_id" => $reservation_id,
        );
        if ($timeout !== 0) {
            $req['timeout'] = (int) $timeout;
        }
        $this->setJsonHeaders();
        $queue = rawurlencode($queue_name);
        $url = "projects/{$this->project_id}/queues/$queue/messages/{$message_id}/touch";
        return self::json_decode($this->apiCall(self::POST, $url, $req));
    }

Touch a Message on a Queue
Touching a reserved message extends its timeout by the duration specified when the message was created,
which is 60 seconds by default.

@param string $queue_name
@param string $message_id
@param int $timeout
@return mixed

Touch a Message on a Queue Touching a reserved message extends its timeout by the duration specified when the message was created which is 60 seconds by default .


public function releaseMessage($queue_name, $message_id, $reservation_id, $delay)
    {
        $this->setJsonHeaders();
        $queue = rawurlencode($queue_name);
        $params = array('reservation_id' => $reservation_id);
        if ($delay !== 0) {
            $params['delay'] = (int) $delay;
        }
        $url = "projects/{$this->project_id}/queues/$queue/messages/{$message_id}/release";
        return self::json_decode($this->apiCall(self::POST, $url, $params));
    }

Release a Message on a Queue
Releasing a reserved message unreserves the message and puts it back on the queue,
as if the message had timed out.

@param string $queue_name
@param string $message_id
@param string $reservation_id
@param int $delay The item will not be available on the queue until this many seconds have passed.
Default is 0 seconds. Maximum is 604,800 seconds (7 days).
@return mixed

Release a Message on a Queue Releasing a reserved message unreserves the message and puts it back on the queue as if the message had timed out .


public function addAlerts($queue_name, $alerts_hash)
    {
        $this->setJsonHeaders();
        $queue = rawurlencode($queue_name);
        $url = "projects/{$this->project_id}/queues/$queue";
        $options = array(
            'queue' => array(
                'alerts' => $alerts_hash,
            ),
        );
        return self::json_decode($this->apiCall(self::PUT, $url, $options));
    }

Add alerts to a queue. This is for Pull Queue only.

@param string $queue_name
@param array $alerts_hash
@return mixed

Add alerts to a queue . This is for Pull Queue only .


public function deleteAlertById($queue_name, $alert_id)
    {
        $this->setJsonHeaders();
        $queue = rawurlencode($queue_name);
        $url = "projects/{$this->project_id}/queues/$queue/alerts/$alert_id";

        return self::json_decode($this->apiCall(self::DELETE, $url));
    }

Remove alert from a queue by its ID. This is for Pull Queue only.

@param string $queue_name
@param string $alert_id
@return mixed
@deprecated

Remove alert from a queue by its ID . This is for Pull Queue only .


public function deleteQueue($queue_name)
    {
        $this->setJsonHeaders();
        $queue = rawurlencode($queue_name);
        $url = "projects/{$this->project_id}/queues/$queue";
        return self::json_decode($this->apiCall(self::DELETE, $url));
    }

Delete a Message Queue
This call deletes a message queue and all its messages.

@param string $queue_name
@return mixed

Delete a Message Queue This call deletes a message queue and all its messages .


public function updateQueue($queue_name, $options)
    {
        $this->setJsonHeaders();
        $queue = rawurlencode($queue_name);
        $url = "projects/{$this->project_id}/queues/$queue";
        return self::json_decode($this->apiCall(self::PATCH, $url, array('queue' => $options)));
    }

Updates the queue object

@param string $queue_name
@param array $options Parameters to change. keys:

@return object


public function createQueue($queue_name, $options)
    {
        $this->setJsonHeaders();
        $queue = rawurlencode($queue_name);
        $url = "projects/{$this->project_id}/queues/$queue";
        return self::json_decode($this->apiCall(self::PUT, $url, array('queue' => $options)));
    }

Creates a queue

@param string $queue_name
@param array $options Parameters to change. keys:

@return object


public function replaceSubscribers($queue_name, $subscribers_hash)
    {
        $this->setJsonHeaders();
        $queue = rawurlencode($queue_name);
        $url = "projects/{$this->project_id}/queues/$queue/subscribers";
        $options = array(
            'subscribers' => $subscribers_hash,
        );
        return self::json_decode($this->apiCall(self::PUT, $url, $options));
    }

Replace old Subscribers with new ones, Older subscribers will be removed.

@param $queue_name
@param $subscribers_hash - Array of subscribers. keys:
- "url" Subscriber url
- "name" Name of subscriber
@return mixed

Replace old Subscribers with new ones Older subscribers will be removed .


public function removeSubscribers($queue_name, $subscriber_hash)
    {
        $this->setJsonHeaders();
        $queue = rawurlencode($queue_name);
        $url = "projects/{$this->project_id}/queues/$queue/subscribers";
        $options = array(
            'subscribers' => $subscriber_hash,
        );
        return self::json_decode($this->apiCall(self::DELETE, $url, $options));
    }

Remove Subscribers from a Queue

Example:
<code>
$ironmq->removeSubscriber("test_queue", array("url" => "http://example.com"));
</code>

@param string $queue_name
@param array $subscriber_hash Subscriber. keys:
- "url" Subscriber url
@return mixed


protected function outputJson(OutputInterface $output, $data)
	{
		$json = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
		$output->write($json);
	}

protected function outputJson ( OutputInterface $ output , $ data ) { $ json = json_encode ( $ data , JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE ) ; $ output -> write ( $ json ) ; }

Generate and output the data as JSON.

@param OutputInterface $output
@param mixed           $data


protected function outputXml(OutputInterface $output, $data)
	{
		$doc               = new \DOMDocument();
		$doc->formatOutput = true;
		$doc->appendChild($this->generateXml($doc, $data));
		$xml = $doc->saveXML();
		$output->write($xml);
	}

protected function outputXml ( OutputInterface $ output , $ data ) { $ doc = new \ DOMDocument ( ) ; $ doc -> formatOutput = true ; $ doc -> appendChild ( $ this -> generateXml ( $ doc , $ data ) ) ; $ xml = $ doc -> saveXML ( ) ; $ output -> write ( $ xml ) ; }

Generate and output the data as XML.

@param OutputInterface $output
@param mixed           $data


protected function generateXml(\DOMDocument $doc, $data)
	{
		if (is_array($data) && range(0, count($data) - 1) == array_keys($data)) {
			// $data is a regular indexed array
			$array = $doc->createElement('array');

			foreach ($data as $value) {
				$entry = $doc->createElement('item');
				$entry->appendChild($this->generateXml($doc, $value));

				$array->appendChild($entry);
			}

			return $array;
		}
		else if (is_array($data) || is_object($data)) {
			// $data is an associative array or object
			$map = $doc->createElement('map');

			foreach ($data as $key => $value) {
				$entry = $doc->createElement('item');
				$entry->setAttribute('key', $key);
				$entry->appendChild($this->generateXml($doc, $value));

				$map->appendChild($entry);
			}

			return $map;
		}
		else {
			// $data is a primitive type
			return $doc->createTextNode($data);
		}
	}

Generate a xml element from the input data.

@param \DOMDocument $doc
@param mixed        $data

@return \DOMElement

Generate a xml element from the input data .


protected function outputCsv(InputInterface $input, OutputInterface $output, $data)
	{
		$delimiter = $input->getOption('delimiter');
		$enclosure = $input->getOption('enclosure');

		$stream = fopen('php://temp', 'w+');

		foreach ($data as $row) {
			if ($enclosure === null) {
				fputcsv($stream, $this->flattenArray($row), $delimiter);
			}
			else {
				fputcsv($stream, $this->flattenArray($row), $delimiter, $enclosure);
			}
		}

		fseek($stream, 0);
		$csv = stream_get_contents($stream);
		$output->write($csv);
	}

protected function outputCsv ( InputInterface $ input , OutputInterface $ output , $ data ) { $ delimiter = $ input -> getOption ( 'delimiter' ) ; $ enclosure = $ input -> getOption ( 'enclosure' ) ; $ stream = fopen ( 'php://temp' , 'w+' ) ; foreach ( $ data as $ row ) { if ( $ enclosure === null ) { fputcsv ( $ stream , $ this -> flattenArray ( $ row ) , $ delimiter ) ; } else { fputcsv ( $ stream , $ this -> flattenArray ( $ row ) , $ delimiter , $ enclosure ) ; } } fseek ( $ stream , 0 ) ; $ csv = stream_get_contents ( $ stream ) ; $ output -> write ( $ csv ) ; }

Generate and output the data as CSV.

@param OutputInterface $output
@param mixed           $data


protected function flattenArray($data)
	{
		if (is_array($data) || is_object($data)) {
			$buffer = array();

			foreach ($data as $item) {
				$buffer = array_merge($buffer, $this->flattenArray($item));
			}

			return $buffer;
		}
		else {
			return (array) $data;
		}
	}

protected function flattenArray ( $ data ) { if ( is_array ( $ data ) || is_object ( $ data ) ) { $ buffer = array ( ) ; foreach ( $ data as $ item ) { $ buffer = array_merge ( $ buffer , $ this -> flattenArray ( $ item ) ) ; } return $ buffer ; } else { return ( array ) $ data ; } }

Flatten an array.

@param $data

@return array


protected function execute(InputInterface $input, OutputInterface $output)
    {
        $debug = $input->getOption('debug');
        $client = $this->getContainer()->get('beryllium_cache.client');

        if (is_object($client) && method_exists($client, 'getStats')) {
            $text = $this->formatStats($client->getStats(), $debug);
        } else {
            $text = 'Active cache client does not have a stats function.';
        }

        $output->writeln($text);
    }

Execute the CLI task

@param InputInterface $input
@param OutputInterface $output
@return void


public function formatStats($stats, $debug = false)
    {
        if (!is_array($stats)) {
            return "No statistics returned.\n";
        }

        if (count($stats) == 0) {
            return "No statistics returned.\n";
        }

        $out = "Servers found: " . count($stats) . "\n\n";
        foreach ($stats as $host => $item) {
            if (!is_array($item) || count($item) == 0) {
                $out .= "  <error>" . $host . "</error>\n";

                continue;
            }

            $out .= "<info>Host:\t" . $host . "</info>\n";

            $out .= "\tUsage: " . $this->formatUsage($item['bytes'], $item['limit_maxbytes']) . "\n";
            $out .= "\tUptime: " . $this->formatUptime($item['uptime']) . "\n";
            $out .= "\tOpen Connections: " . $item['curr_connections'] . "\n";
            $out .= "\tHits: " . $item['get_hits'] . "\n";
            $out .= "\tMisses: " . $item['get_misses'] . "\n";
            if ($item['get_hits'] + $item['get_misses'] > 0) {
                $out .= "\tHelpfulness: " . round(
                    $item['get_hits'] / ($item['get_hits'] + $item['get_misses']) * 100,
                    2
                ) . "%\n";
            }

            if ($debug) {
                $out .= "\n";
                foreach ($item as $key => $value) {
                    $out .= "\t" . $key . ': ' . $value . "\n";
                }
            }
        }

        return $out;
    }

public
function
formatStats
(
$
stats
,
$
debug
=
false
)
{
if
(
!
is_array
(
$
stats
)
)
{
return
"No statistics returned.\n"
;
}
if
(
count
(
$
stats
)
==
0
)
{
return
"No statistics returned.\n"
;
}
$
out
=
"Servers found: "
.
count
(
$
stats
)
.
"\n\n"
;
foreach
(
$
stats
as
$
host
=>
$
item
)
{
if
(
!
is_array
(
$
item
)
||
count
(
$
item
)
==
0
)
{
$
out
.=
"  <error>"
.
$
host
.
"</error>\n"
;
continue
;
}
$
out
.=
"<info>Host:\t"
.
$
host
.
"</info>\n"
;
$
out
.=
"\tUsage: "
.
$
this
->
formatUsage
(
$
item
[
'bytes'
]
,
$
item
[
'limit_maxbytes'
]
)
.
"\n"
;
$
out
.=
"\tUptime: "
.
$
this
->
formatUptime
(
$
item
[
'uptime'
]
)
.
"\n"
;
$
out
.=
"\tOpen Connections: "
.
$
item
[
'curr_connections'
]
.
"\n"
;
$
out
.=
"\tHits: "
.
$
item
[
'get_hits'
]
.
"\n"
;
$
out
.=
"\tMisses: "
.
$
item
[
'get_misses'
]
.
"\n"
;
if
(
$
item
[
'get_hits'
]
+
$
item
[
'get_misses'
]
>
0
)
{
$
out
.=
"\tHelpfulness: "
.
round
(
$
item
[
'get_hits'
]
/
(
$
item
[
'get_hits'
]
+
$
item
[
'get_misses'
]
)
*
100
,
2
)
.
"%\n"
;
}
if
(
$
debug
)
{
$
out
.=
"\n"
;
foreach
(
$
item
as
$
key
=>
$
value
)
{
$
out
.=
"\t"
.
$
key
.
': '
.
$
value
.
"\n"
;
}
}
}
return
$
out
;
}

Format the raw array for the command line report

@param array $stats An array of memcache::extendedstats
@param bool $debug (default: false) True causes a raw dump of the stats array to be provided
@return string ConsoleComponent-formatted output, suitable for ->writeln() usage


public function formatUsage($bytes, $maxbytes)
    {
        if (!is_numeric($maxbytes) || $maxbytes < 1) {
            return '(undefined)';
        }

        $out = round($bytes / $maxbytes, 3) . "% (";
        $out .= round($bytes / 1024 / 1024, 2) . 'MB of ';
        $out .= round($maxbytes / 1024 / 1024, 2) . 'MB)';

        return $out;
    }

public
function
formatUsage
(
$
bytes
,
$
maxbytes
)
{
if
(
!
is_numeric
(
$
maxbytes
)
||
$
maxbytes
<
1
)
{
return
'(undefined)'
;
}
$
out
=
round
(
$
bytes
/
$
maxbytes
,
3
)
.
"% ("
;
$
out
.=
round
(
$
bytes
/
1024
/
1024
,
2
)
.
'MB of '
;
$
out
.=
round
(
$
maxbytes
/
1024
/
1024
,
2
)
.
'MB)'
;
return
$
out
;
}

Format the usage stats

@param integer $bytes Cache usage (in bytes)
@param integer $maxbytes Cache maximum size (in bytes)
@return string A short string with friendly formatting


public function formatUptime($uptime)
    {
        $days = floor($uptime / 24 / 60 / 60);
        $days_remainder = $uptime - ($days * 24 * 60 * 60);
        $hours = floor($days_remainder / 60 / 60);
        $hours_remainder = $days_remainder - ($hours * 60 * 60);
        $minutes = floor($hours_remainder / 60);
        $minutes_remainder = $hours_remainder - ($minutes * 60);
        $seconds = $minutes_remainder;
        $out = $uptime . ' seconds (';

        if ($days > 0) {
            $out .= $days . ' days, ';
        }

        if ($hours > 0) {
            $out .= $hours . ' hours, ';
        }

        if ($minutes > 0) {
            $out .= $minutes . ' minutes, ';
        }

        if ($seconds > 0) {
            $out .= $seconds . ' seconds';
        }

        return $out . ')';
    }

public
function
formatUptime
(
$
uptime
)
{
$
days
=
floor
(
$
uptime
/
24
/
60
/
60
)
;
$
days_remainder
=
$
uptime
(
$
days
*
24
*
60
*
60
)
;
$
hours
=
floor
(
$
days_remainder
/
60
/
60
)
;
$
hours_remainder
=
$
days_remainder
(
$
hours
*
60
*
60
)
;
$
minutes
=
floor
(
$
hours_remainder
/
60
)
;
$
minutes_remainder
=
$
hours_remainder
(
$
minutes
*
60
)
;
$
seconds
=
$
minutes_remainder
;
$
out
=
$
uptime
.
' seconds ('
;
if
(
$
days
>
0
)
{
$
out
.=
$
days
.
' days, '
;
}
if
(
$
hours
>
0
)
{
$
out
.=
$
hours
.
' hours, '
;
}
if
(
$
minutes
>
0
)
{
$
out
.=
$
minutes
.
' minutes, '
;
}
if
(
$
seconds
>
0
)
{
$
out
.=
$
seconds
.
' seconds'
;
}
return
$
out
.
')'
;
}

Formats the uptime to be friendlier

@param integer $uptime Cache server uptime (in seconds)
@return string A short string with friendly formatting


public function addServer($ip, $port = 11211)
    {
        if (is_object($this->mem)) {
            return $this->mem->addServer($ip, $port);
        }
    }

public function addServer ( $ ip , $ port = 11211 ) { if ( is_object ( $ this -> mem ) ) { return $ this -> mem -> addServer ( $ ip , $ port ) ; } }

Add a server to the memcache pool.

Does not probe server, does not set Safe to true.

Should really be private, or modified to handle the probeServer action itself.

@param string $ip Location of memcache server
@param int $port Optional: Port number (default: 11211)
@access public
@return void


public function addServers(array $servers)
    {
        if (count($servers) == 0) {
            return false;
        }

        foreach ($servers as $ip => $port) {
            if (intval($port) == 0) {
                $port = null;
            }

            if ($this->probeServer($ip, $port)) {
                $status = $this->addServer($ip, $port);
                $this->safe = true;
            }
        }
    }

public function addServers ( array $ servers ) { if ( count ( $ servers ) == 0 ) { return false ; } foreach ( $ servers as $ ip => $ port ) { if ( intval ( $ port ) == 0 ) { $ port = null ; } if ( $ this -> probeServer ( $ ip , $ port ) ) { $ status = $ this -> addServer ( $ ip , $ port ) ; $ this -> safe = true ; } } }

Add an array of servers to the memcache pool

Uses ProbeServer to verify that the connection is valid.

Format of array:

$servers[ '127.0.0.1' ] = 11211;

Logic is somewhat flawed, of course, because it wouldn't let you add multiple
servers on the same IP.

Serious flaw, right? ;-)

@param array $servers See above format definition
@access public
@return void


public function probeServer($ip, $port)
    {
        $errno = null;
        $errstr = null;
        $fp = @fsockopen($ip, $port, $errno, $errstr, $this->sockttl);

        if ($fp) {
            fclose($fp);

            return true;
        } else {
            return false;
        }
    }

public function probeServer ( $ ip , $ port ) { $ errno = null ; $ errstr = null ; $ fp = @ fsockopen ( $ ip , $ port , $ errno , $ errstr , $ this -> sockttl ) ; if ( $ fp ) { fclose ( $ fp ) ; return true ; } else { return false ; } }

Spend a few tenths of a second opening a socket to the requested IP and port

The purpose of this is to verify that the server exists before trying to add it,
to cut down on weird errors when doing ->get(). This could be a controversial or
flawed way to go about this.

@param string $ip IP address (or hostname, possibly)
@param int $port Port that memcache is running on
@access public
@return boolean True if the socket opens successfully, or false if it fails


public function get($key)
    {
        if ($this->isSafe()) {
            $key = $this->prefix . $key;
            return $this->mem->get($key);
        }

        return false;
    }

public function get ( $ key ) { if ( $ this -> isSafe ( ) ) { $ key = $ this -> prefix . $ key ; return $ this -> mem -> get ( $ key ) ; } return false ; }

Retrieve a value from memcache

@param string|array $key Unique identifier or array of identifiers
@access public
@return mixed Requested value, or false if an error occurs


public function set($key, $value, $ttl)
    {
        if ($this->isSafe()) {
            $key = $this->prefix . $key;
            return $this->mem->set($key, $value, $this->compression, $ttl);
        }

        return false;
    }

public function set ( $ key , $ value , $ ttl ) { if ( $ this -> isSafe ( ) ) { $ key = $ this -> prefix . $ key ; return $ this -> mem -> set ( $ key , $ value , $ this -> compression , $ ttl ) ; } return false ; }

Add a value to the memcache

@param string $key Unique key
@param mixed $value A value. I recommend a string, be it serialized or not - other values haven't been tested :)
@param int $ttl Number of seconds for the value to be valid for
@access public
@return void


public function delete($key)
    {
        if ($this->isSafe()) {
            $key = $this->prefix . $key;
            return $this->mem->delete($key, 0);
        }

        return false;
    }

public function delete ( $ key ) { if ( $ this -> isSafe ( ) ) { $ key = $ this -> prefix . $ key ; return $ this -> mem -> delete ( $ key , 0 ) ; } return false ; }

Delete a value from the memcache

@param string $key Unique key
@access public
@return void


public function setClient(CacheClientInterface $client)
    {
        if (is_object($client) && ($client instanceof CacheClientInterface))
            $this->client = $client;
        else {
            throw new \Exception('Invalid Cache Client Interface');
        }
    }

public
function
setClient
(
CacheClientInterface
$
client
)
{
if
(
is_object
(
$
client
)
&&
(
$
client
instanceof
CacheClientInterface
)
)
$
this
->
client
=
$
client
;
else
{
throw
new
\
Exception
(
'Invalid Cache Client Interface'
)
;
}
}

Inject a cache client interface to interact with a custom cache service

@param CacheClientInterface $client The client object or service
@access public
@return void


public function get($key)
    {
        if ($this->isSafe() && !empty($key)) {
            return $this->client->get($key);
        }

        return false;
    }

public function get ( $ key ) { if ( $ this -> isSafe ( ) && ! empty ( $ key ) ) { return $ this -> client -> get ( $ key ) ; } return false ; }

Retrieve a value from the cache using the provided key

@param string|array $key The unique key or array of keys identifying the data to be retrieved.
@access public
@return mixed The requested data, or false if there is an error


public function delete($key)
    {
        if ($this->isSafe() && !empty($key)) {
            return $this->client->delete($key);
        }

        return false;
    }

public function delete ( $ key ) { if ( $ this -> isSafe ( ) && ! empty ( $ key ) ) { return $ this -> client -> delete ( $ key ) ; } return false ; }

Delete a key from the cache

@param string $key Unique key
@access public
@return void


protected static function makeInvalidArgumentException($data, $method, $container, $builder)
    {
        $type = gettype($data);
        if (is_object($data)) {
            $type = get_class($data);
        }

        return new InvalidArgumentException(
           'The argument for %s::%s must be instanceof %s, %s, null or array. %s given.',
            [
                self::class, $method, $container, $builder, $type,
            ]
        );
    }

Make Invalid Argument Exception.

@param  mixed  $data
@param  string $method
@param  string $container
@param  string $builder
@return \NotificationChannels\FCM\Exceptions\InvalidArgumentException


protected static function populateBuilder($builder, array $map, array $data)
    {
        foreach ($map as $key => $method) {
            $value = Arr::get($data, $key);
            $builder->{$method}($value);
        }

        return $builder;
    }

protected static function populateBuilder ( $ builder , array $ map , array $ data ) { foreach ( $ map as $ key => $ method ) { $ value = Arr :: get ( $ data , $ key ) ; $ builder -> { $ method } ( $ value ) ; } return $ builder ; }

Populate Builder.

@param  object $builder
@param  array  $map
@param  array  $data
@return object