2015-03-02 21:57:49 +01:00
< ? php
namespace Trinity\Bundle\AdminBundle\Controller ;
use \BasePeer ;
use Symfony\Bundle\FrameworkBundle\Controller\Controller ;
use Symfony\Component\HttpFoundation\Request ;
use Symfony\Component\HttpFoundation\Response ;
use Symfony\Component\HttpFoundation\Cookie ;
use Symfony\Component\HttpFoundation\File\File ;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route ;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template ;
use Pagerfanta\Adapter\PropelAdapter ;
use Pagerfanta\Pagerfanta ;
use Pagerfanta\Exception\NotValidCurrentPageException ;
use Trinity\Bundle\AdminBundle\Exception\FilterMethodNotFoundException ;
use Trinity\Bundle\AdminBundle\Form\Type\BatchType ;
use Trinity\Bundle\AdminBundle\Form\Type\RankType ;
use Trinity\Bundle\UserBundle\Flash\FlashError ;
use Trinity\Bundle\UserBundle\Flash\FlashSuccess ;
use Trinity\Bundle\UserBundle\Flash\FlashWarning ;
use Trinity\Bundle\AdminBundle\Exception\RequestAdminException ;
use Trinity\Component\Utils\Propel ;
/**
* @ Route ( " /admin " )
*/
class BaseAdminController extends Controller
{
const UPLOAD_INTERFACE = 'Trinity\Component\File\FileUploadInterface' ;
const HISTORY_LIMIT = 10 ;
protected $configuration ;
public function flashAction ()
{
$user = $this -> getSessionUser ();
if ( ! $user -> hasFlash ( 'message' , $this -> getConfiguration () -> getStorageNamespace ())) {
return new Response ();
}
$flash = $user -> getFlash (
'message' ,
$this -> getConfiguration () -> getStorageNamespace ()
);
return $this -> render (
$flash -> getTemplate (),
array (
'message' => $flash -> getMessage ()
)
);
}
public function filtersAction ( $routePrefix )
{
return $this -> render (
'TrinityAdminBundle:BaseAdmin:filters.html.twig' ,
array (
'form_filter' => $this -> getFormFilter () -> createView (),
'filter_display_fields' => $this -> getConfiguration () -> getFilterDisplayFields (),
'filters_templates' => $this -> getConfiguration () -> getFiltersTemplates (),
'user_has_filter' => $this -> getSessionUser () -> getAttribute ( 'filter' , false , $this -> getConfiguration () -> getStorageNamespace ()),
'route_prefix' => $routePrefix ,
)
);
}
public function historyAction ( $routePrefix )
{
$query = $this -> getQuery ();
try {
$query -> orderByUpdatedAt ( \Criteria :: DESC );
} catch ( \PropelException $e ) {
}
$query -> limit ( self :: HISTORY_LIMIT );
return $this -> render (
'TrinityAdminBundle:BaseAdmin:history.html.twig' ,
array (
'objects' => $query -> find (),
'route_prefix' => $routePrefix ,
)
);
}
protected function getQuery ()
{
$modelQuery = $this -> getConfiguration () -> getModelQuery ();
return $modelQuery :: create ();
}
protected function addSortToQuery ( & $query )
{
if ( ! $this -> getConfiguration () -> getSortOrder ()) {
return false ;
}
$method = $this -> getConfiguration () -> getSort ();
2015-03-09 23:29:12 +01:00
$method = $this -> getConfiguration () -> getRankable () ? 'orderByRank' : $method ;
2015-03-02 21:57:49 +01:00
if ( ! $method ) {
return false ;
}
try {
call_user_func ( array ( $query , $method ), $this -> getConfiguration () -> getSortOrder ());
} catch ( \PropelException $e ) {
}
return true ;
}
protected function getFilters ( Request $request )
{
if ( $request -> isMethod ( 'POST' )) {
$datas = $request -> request -> get ( $this -> getFormFilter ( true ) -> getName ());
} else {
$datas = $request -> query -> get ( $this -> getFormFilter ( true ) -> getName ());
}
if ( ! empty ( $datas )) {
return $datas ;
}
return $this -> getSessionUser () -> getAttribute (
'filter' ,
array (),
$this -> getConfiguration () -> getStorageNamespace ()
);
}
protected function addFiltersToQuery ( & $query , Request $request )
{
$form = $this -> getFormFilter ( true );
$datas = $this -> getFilters ( $request );
if ( ! is_array ( $datas )) {
return false ;
}
$datas = $this -> cleanFilterArray ( $datas );
$filtersMethods = $this -> getConfiguration () -> getFiltersMethods ();
foreach ( $datas as $field => $value ) {
$method = isset ( $filtersMethods [ $field ]) ? $filtersMethods [ $field ][ 'method' ] : 'filterBy' . Propel :: camelCase ( $field );
$criteria = isset ( $filtersMethods [ $field ]) ? $filtersMethods [ $field ][ 'criteria' ] : ( is_numeric ( $value ) && intval ( $value ) == $value ? null : 'like' );
$params = isset ( $filtersMethods [ $field ]) ? $filtersMethods [ $field ][ 'params' ] : array ();
if ( ! method_exists ( $this -> getConfiguration () -> getModelQuery (), $method )) {
throw new FilterMethodNotFoundException ( sprintf ( 'Filter method "%s" does not exist in class "%s"' , $method , $this -> getConfiguration () -> getModelQuery ()));
}
if ( strtolower ( $criteria ) == 'like' ) {
$value = '%' . $value . '%' ;
$criteria = null ;
}
if ( $value !== 'bool.both' && $value !== '%bool.both%' ) {
$bools = array (
'bool.true' => true ,
'bool.false' => false ,
'%bool.true%' => true ,
'%bool.false%' => false ,
);
if ( isset ( $bools [ $value ])) {
$value = $bools [ $value ];
}
try {
$this -> get ( 'logger' ) -> info ( sprintf ( 'Filter by "%s" with "%s", criteria: %s' , $method , var_export ( $value , true ), $criteria ? $criteria : 'NULL' ));
$callParams = array_merge ( $criteria !== null ? array ( $value , $criteria ) : array ( $value ), $params );
call_user_func_array ( array ( $query , $method ), $callParams );
} catch ( \PropelException $e ) {
}
} else {
unset ( $datas [ $field ]);
}
}
$filterMethod = $this -> getConfiguration () -> getFilter ();
if ( $filterMethod !== null ) {
if ( ! method_exists ( $this -> getConfiguration () -> getModelQuery (), $filterMethod )) {
throw new FilterMethodNotFoundException ( sprintf ( 'Filter method "%s" does not exist in class "%s"' , $filterMethod , $this -> getConfiguration () -> getModelQuery ()));
}
$value = $this -> getConfiguration () -> getFilterValue ();
if ( ! is_array ( $value )) {
$value = array ( $value );
}
$this -> get ( 'logger' ) -> info ( sprintf ( 'Filter by "%s" with "%s"' , $filterMethod , var_export ( $value , true )));
call_user_func_array ( array ( $query , $filterMethod ), $value );
}
$this -> getSessionUser () -> setAttribute ( 'filter' , $datas , $this -> getConfiguration () -> getStorageNamespace ());
$form -> bind ( $datas );
return $form ;
}
protected function getPager ( Request $request )
{
$query = $this -> getQuery ();
$query -> distinct ();
$this -> addSortToQuery ( $query );
$this -> addFiltersToQuery ( $query , $request );
$adapter = new PropelAdapter ( $query );
$pagerfanta = new Pagerfanta ( $adapter );
$pagerfanta -> setMaxPerPage ( $this -> getConfiguration () -> getMaxPerPage ());
try {
$pagerfanta -> setCurrentPage ( $this -> getConfiguration () -> getCurrentPage (), false , true );
} catch ( NotValidCurrentPageException $e ) {
$pagerfanta -> setCurrentPage ( 1 , false , true );
}
return $pagerfanta ;
}
protected function getFields ()
{
$modelPeer = $this -> getConfiguration () -> getModelPeer ();
$peerFields = $modelPeer :: getFieldNames ( BasePeer :: TYPE_FIELDNAME );
$peerFieldsCb = $modelPeer :: getFieldNames ();
$fields = array ();
$finalFields = array ();
$displayFields = $this -> getConfiguration () -> getDisplayFields ();
$fieldsTemplates = $this -> getConfiguration () -> getFieldsTemplates ();
if ( ! empty ( $displayFields )) {
$arrayPushBefore = function ( array $array , $data , $pos ) {
return array_merge ( array_slice ( $array , 0 , $pos ), array ( $data ), array_slice ( $array , $pos ));
};
foreach ( $displayFields as $k => $displayField ) {
if ( ! in_array ( $displayField , $peerFields )) {
$method = ucfirst ( $displayField );
$peerFields = $arrayPushBefore ( $peerFields , $displayField , $k );
$peerFieldsCb = $arrayPushBefore ( $peerFieldsCb , $method , $k );
}
}
}
$fieldNames = new \ArrayIterator ( $peerFields );
$fieldNamesCb = new \ArrayIterator ( $peerFieldsCb );
while ( $fieldNames -> valid ()) {
if ( empty ( $displayFields ) || ( ! empty ( $displayFields ) && in_array ( $fieldNames -> current (), $displayFields ))) {
$method1 = Propel :: getGetter ( $fieldNamesCb -> current ());
$method2 = lcfirst ( preg_replace ( '/^get/' , '' , $method1 ));
$data = array (
'name' => $fieldNames -> current (),
'method' => method_exists ( $this -> getConfiguration () -> getModel (), $method2 ) ? $method2 : $method1 ,
'template' => isset ( $fieldsTemplates [ $fieldNames -> current ()]) ? $fieldsTemplates [ $fieldNames -> current ()] : $this -> getConfiguration () -> getDefaultFieldTemplate ()
);
if ( empty ( $displayFields )) {
$fields [] = $data ;
} else {
$keys = array_keys ( $displayFields , $fieldNames -> current ());
$fields [ $keys [ 0 ]] = $data ;
}
}
$fieldNames -> next ();
$fieldNamesCb -> next ();
}
$k = 0 ;
while ( count ( $finalFields ) !== count ( $fields )) {
if ( isset ( $fields [ $k ])) {
$finalFields [] = $fields [ $k ];
}
$k ++ ;
}
return $finalFields ;
}
protected function redirectByRequest ( Request $request , $object )
{
$list = array (
'edit_same' => $this -> generateUrl ( sprintf ( '%s_edit' , $this -> getConfiguration () -> getRoutePrefix ()), array ( 'id' => $object -> getId ())),
'save_new' => $this -> generateUrl ( sprintf ( '%s_new' , $this -> getConfiguration () -> getRoutePrefix ())),
);
foreach ( $list as $index => $uri ) {
if ( $request -> request -> has ( $index )) {
return $uri ;
}
}
throw new RequestAdminException ( 'No valid target (post submit) has been found.' );
}
protected function getBatchType ()
{
return $this -> createForm ( new BatchType ());
}
protected function getRankType ()
{
return $this -> createForm ( new RankType ());
}
protected function processForm ( & $form , & $object , Request $request )
{
$form -> bind ( $request );
if ( $form -> isValid ()) {
if ( $object instanceof \FOS\UserBundle\Propel\User ) {
if ( $object -> isNew ()) {
$newUser = true ;
} else {
$updatedUser = true ;
}
}
$this -> preSave ( $object );
$object -> save ();
$this -> postSave ( $object );
if ( ! empty ( $newUser )) {
$this -> get ( 'trinity.user_log' ) -> created ( $object , $this -> getUser ());
}
if ( ! empty ( $updatedUser )) {
$this -> get ( 'trinity.user_log' ) -> updated ( $object , $this -> getUser ());
}
return $this -> redirect ( $this -> redirectByRequest ( $request , $object ));
}
return false ;
}
protected function removeObjects ( $query , array $pks )
{
foreach ( $pks as $pk ) {
$object = $query -> findPK ( $pk );
$this -> preRemove ( $object );
$object -> delete ();
$this -> postRemove ( $object );
}
}
protected function copyObjects ( $query , array $pks )
{
foreach ( $pks as $pk ) {
$copy = $query -> findPK ( $pk ) -> copy ( true );
$this -> preSave ( $copy );
$copy -> save ();
$this -> postSave ( $copy );
}
}
protected function processBatchForm ( & $form , Request $request )
{
$form -> submit ( $request );
//if ($form->isValid()) {
$values = $request -> request -> get ( $form -> getName ());
if ( ! empty ( $values [ 'objects' ])) {
$modelQuery = $this -> getConfiguration () -> getModelQuery ();
$query = new $modelQuery ();
switch ( $values [ 'action' ]) {
case BatchType :: BATCH_COPY : $this -> copyObjects ( $query , $values [ 'objects' ]); break ;
case BatchType :: BATCH_REMOVE : $this -> removeObjects ( $query , $values [ 'objects' ]); break ;
}
$this -> get ( 'logger' ) -> info ( sprintf ( 'Batch action (%s)' , $values [ 'action' ]));
return 2 ;
}
return 1 ;
//}
return 0 ;
}
protected function batchAction ( Request $request )
{
$form = $this -> getBatchType ();
$redirect = $this -> redirect (
$this -> getSessionUser () -> getAttribute (
'referer' ,
$this -> generateUrl ( sprintf ( '%s_index' , $this -> getConfiguration () -> getRoutePrefix ()), array ( 'page' => 1 ))
)
);
$proccess = $this -> processBatchForm ( $form , $request );
$namespace = $this -> getConfiguration () -> getStorageNamespace ();
switch ( $proccess ) {
case 1 : $this -> getSessionUser () -> setFlash ( 'message' , new FlashWarning ( 'crud.flash.notselected' ), false , $namespace ); break ;
case 2 : $this -> getSessionUser () -> setFlash ( 'message' , new FlashSuccess ( 'crud.flash.updated.plural' ), false , $namespace ); break ;
}
return $redirect ;
}
/**
* @ Route ( " / " , name = " TrinityAdminBundle_index " )
*/
public function indexAction ( $page , Request $request )
{
$this -> getSessionUser () -> setAttribute ( 'referer' , $request -> getRequestUri ());
$namespace = $this -> getConfiguration () -> getStorageNamespace ();
$sortCookieName = $namespace . '_sort' ;
$pageCookieName = $namespace . '_page' ;
$sort = '' ;
if ( $request -> query -> get ( 'sort' )) {
$sort = $request -> query -> get ( 'sort' );
} elseif ( $sortCookie = $request -> cookies -> get ( $sortCookieName )) {
$sort = $sortCookie ;
}
if ( ! $request -> query -> has ( 'sort' ) && intval ( $page ) === 1 ) {
if ( $pageCookie = $request -> cookies -> get ( $pageCookieName )) {
$page = max ( 1 , intval ( $pageCookie ));
}
}
if ( $format = $request -> query -> get ( 'format' )) {
if ( $this -> isValidExportFormat ( $format )) {
return $this -> exportTo ( $format );
}
}
$this -> getConfiguration () -> setCurrentPage ( $page );
$this -> addCookie ( new Cookie ( $pageCookieName , $page , time () + 3600 ));
if ( ! empty ( $sort )) {
$parts = explode ( ':' , $sort );
if ( count ( $parts ) == 2 ) {
list ( $field , $order ) = $parts ;
$method = 'orderBy' . Propel :: camelCase ( $field );
$this -> getConfiguration () -> setSort ( $method , $order );
$this -> get ( 'logger' ) -> info ( sprintf ( 'Order by "%s", "%s"' , $method , $order ));
$this -> addCookie ( new Cookie ( $sortCookieName , $sort , time () + 3600 * 24 * 360 ));
}
}
$pager = $this -> getPager ( $request );
if ( $this -> getConfiguration () -> getRedirectIfOneResult ()) {
if ( $this -> getFilters ( $request ) && count ( $pager ) === 1 && $this -> getConfiguration () -> getIndexListAction ( 'edit' )) {
$this -> getSessionUser () -> setAttribute ( 'filter' , null , $this -> getConfiguration () -> getStorageNamespace ());
return $this -> redirect ( $this -> generateUrl ( sprintf ( '%s_edit' , $this -> getConfiguration () -> getRoutePrefix ()), array ( 'id' => $pager -> getIterator () -> offsetGet ( 0 ) -> getId ())));
}
}
return array (
'pager' => $pager ,
'fields' => $this -> getFields (),
'fields_templates' => $this -> getConfiguration () -> getFieldsTemplates (),
'fields_attrs' => $this -> getConfiguration () -> getDisplayFieldsAttrs (),
'list_actions' => $this -> getConfiguration () -> getIndexListActions (),
'index_actions' => $this -> getConfiguration () -> getIndexActions (),
'batch_actions' => $this -> getConfiguration () -> getBatchActions (),
'context_menu' => $this -> getConfiguration () -> getContextMenu (),
'export' => $this -> getConfiguration () -> getExport (),
'exportFormats' => $this -> getConfiguration () -> getExportFormats (),
'rankable' => $this -> getConfiguration () -> getRankable (),
'remove_token' => $this -> getRemoveToken ( true ),
'fieldsnames' => $this -> getConfiguration () -> getFieldsnames (),
'templating' => $this -> container -> get ( 'templating' ),
'form_batch' => $this -> getBatchType () -> createView (),
'form_rank' => $this -> getRankType () -> createView (),
'title' => $this -> getConfiguration () -> getListTitle (),
'i18n' => $this -> getConfiguration () -> getI18n (),
'i18n_cultures' => $this -> getConfiguration () -> getI18nCultures (),
'pager_sort' => $sort ,
);
}
protected function addCookie ( Cookie $cookie )
{
$response = new Response ();
$response -> headers -> setCookie ( $cookie );
return $response -> send ();
}
protected function exportTo ( $format )
{
$query = $this -> getQuery ();
$this -> addSortToQuery ( $query );
$this -> addFiltersToQuery ( $query , $this -> getRequest ());
$render = $this -> render (
'TrinityAdminBundle:BaseAdmin:export.html.twig' ,
array (
'datas' => $query -> find () -> exportTo ( $format ),
)
);
$render -> headers -> set ( 'Content-Type' , $this -> getExportContentTypeByFormat ( $format ));
$render -> headers -> set ( 'Content-disposition' , sprintf ( 'filename="export-%s%s"' , time (), $this -> getExportExtensionByFormat ( $format )));
return $render ;
}
public function clearFilterAction ( Request $request )
{
$redirect = $this -> redirect (
$this -> getSessionUser () -> getAttribute (
'referer' ,
$this -> generateUrl ( sprintf ( '%s_index' , $this -> getConfiguration () -> getRoutePrefix ()), array ( 'page' => 1 ))
)
);
$this -> getSessionUser () -> setAttribute ( 'filter' , null , $this -> getConfiguration () -> getStorageNamespace ());
return $redirect ;
}
public function editAction ( $object , Request $request )
{
if ( ! $object ) {
$this -> getSessionUser () -> setFlash ( 'message' , new FlashWarning ( 'crud.flash.unknown' ), false , $this -> getConfiguration () -> getStorageNamespace ());
return $this -> redirect ( $this -> generateUrl ( sprintf ( '%s_index' , $this -> getConfiguration () -> getRoutePrefix ())));
}
$form = $this -> getConfiguration () -> getFormEdit ();
2015-03-09 23:29:12 +01:00
if ( $this -> has ( $form )){
$form = $this -> createForm ( $this -> get ( $form ) -> getName (), $object , $this -> getConfiguration () -> getFormEditOptions ());
} else {
$form = $this -> createForm ( new $form ( $this -> getConfiguration () -> getFormEditOptions ()), $object );
}
2015-03-02 21:57:49 +01:00
if ( 'POST' === $request -> getMethod ()) {
if ( false !== $processForm = $this -> processForm ( $form , $object , $request )) {
$this -> getSessionUser () -> setFlash ( 'message' , new FlashSuccess ( 'crud.flash.updated.singular' ), false , $this -> getConfiguration () -> getStorageNamespace ());
return $processForm ;
}
$this -> getSessionUser () -> setFlash ( 'message' , new FlashError ( 'crud.flash.fail.update' ), false , $this -> getConfiguration () -> getStorageNamespace ());
}
return array (
'object' => $object ,
'created_at' => ( method_exists ( $object , 'getCreatedAt' )) ? $object -> getCreatedAt ( 'd/m/Y' ) : null ,
'updated_at' => ( method_exists ( $object , 'getUpdatedAt' )) ? $object -> getUpdatedAt ( 'd/m/Y' ) : null ,
'form' => $form -> createView (),
'fieldsets' => $this -> getConfiguration () -> getFieldsets (),
'fieldsetsView' => $this -> getConfiguration () -> getFieldsetsView (),
'fieldsnames' => $this -> getConfiguration () -> getFieldsnames (),
'fields_helpers' => $this -> getConfiguration () -> getFieldsHelpers (),
'remove_token' => $this -> getRemoveToken ( true ),
'title' => $this -> getConfiguration () -> getEditTitle ( $object ),
'i18n' => $this -> getConfiguration () -> getI18n (),
'i18n_cultures' => $this -> getConfiguration () -> getI18nCultures (),
'collections' => $this -> getConfiguration () -> getCollections (),
);
}
public function newAction ( Request $request )
{
$model = $this -> getConfiguration () -> getModel ();
$object = new $model ();
2015-03-09 23:29:12 +01:00
2015-03-02 21:57:49 +01:00
$form = $this -> getConfiguration () -> getFormNew ();
2015-03-09 23:29:12 +01:00
if ( $this -> has ( $form )){
$form = $this -> createForm ( $this -> get ( $form ) -> getName (), $object , $this -> getConfiguration () -> getFormNewOptions ());
} else {
$form = $this -> createForm ( new $form ( $this -> getConfiguration () -> getFormNewOptions ()), $object );
}
2015-03-02 21:57:49 +01:00
if ( 'POST' === $request -> getMethod ()) {
if ( false !== $processForm = $this -> processForm ( $form , $object , $request )) {
$this -> getSessionUser () -> setFlash ( 'message' , new FlashSuccess ( 'crud.flash.updated.singular' ), false , $this -> getConfiguration () -> getStorageNamespace ());
return $processForm ;
}
$this -> getSessionUser () -> setFlash ( 'message' , new FlashError ( 'crud.flash.fail.new' ), false , $this -> getConfiguration () -> getStorageNamespace ());
}
return array (
'form' => $form -> createView (),
'fieldsets' => $this -> getConfiguration () -> getFieldsets (),
'fieldsetsView' => $this -> getConfiguration () -> getFieldsetsView (),
'fieldsnames' => $this -> getConfiguration () -> getFieldsnames (),
'fields_helpers' => $this -> getConfiguration () -> getFieldsHelpers (),
'title' => $this -> getConfiguration () -> getNewTitle (),
'i18n' => $this -> getConfiguration () -> getI18n (),
'i18n_cultures' => $this -> getConfiguration () -> getI18nCultures (),
'collections' => $this -> getConfiguration () -> getCollections (),
);
}
public function removeAction ( $object , $token , Request $request )
{
if ( $object ) {
if ( $this -> getRemoveToken () !== $token ) {
$this -> getSessionUser () -> setFlash ( 'message' , new FlashError ( 'crud.flash.token' ), false , $this -> getConfiguration () -> getStorageNamespace ());
} else {
try {
$this -> preRemove ( $object );
$object -> delete ();
$this -> postRemove ( $object );
$this -> getSessionUser () -> setFlash ( 'message' , new FlashSuccess ( 'crud.flash.removed' ), false , $this -> getConfiguration () -> getStorageNamespace ());
} catch ( PropelException $e ) {
$this -> getSessionUser () -> setFlash ( 'message' , new FlashError ( 'crud.flash.fail.remove' ), false , $this -> getConfiguration () -> getStorageNamespace ());
}
}
} else {
$this -> getSessionUser () -> setFlash ( 'message' , new FlashWarning ( 'crud.flash.unknown' ), false , $this -> getConfiguration () -> getStorageNamespace ());
}
return $this -> redirect ( $this -> generateUrl ( sprintf ( '%s_index' , $this -> getConfiguration () -> getRoutePrefix ())));
}
public function rankAction ( Request $request )
{
$form = $this -> getRankType ();
$form -> bind ( $request );
if ( $form -> isValid ()) {
$datas = $form -> getData ();
$ids = explode ( ' ' , $datas [ 'objects' ]);
$page = $datas [ 'page' ];
$query = $this -> getQuery ();
foreach ( $ids as $k => $id ) {
$rank = ( $this -> getConfiguration () -> getMaxPerPage () * $page ) + $k + 1 ;
$object = $query -> findOneById ( $id );
if ( $object ) {
$object -> setRank ( $rank ) -> save ();
}
}
}
return null ;
}
protected function getRemoveToken ( $getNew = false )
{
$attributeName = 'remove_token_' . $this -> getConfiguration () -> getModel ();
if ( $getNew ) {
$token = sha1 ( uniqid () . time ());
$this -> getSessionUser () -> setAttribute ( $attributeName , $token );
return $token ;
}
return $this -> getSessionUser () -> getAttribute ( $attributeName );
}
protected function isValidExportFormat ( $format )
{
return in_array ( $format , array ( 'XML' , 'CSV' , 'JSON' , 'YAML' ));
}
protected function getExportContentTypeByFormat ( $format )
{
if ( ! $this -> isValidExportFormat ( $format )) {
return null ;
}
$formats = array (
'XML' => 'text/xml' ,
'CSV' => 'text/csv' ,
'JSON' => 'text/json' ,
'YAML' => 'text/yaml' ,
);
return $formats [ $format ];
}
protected function getExportExtensionByFormat ( $format )
{
if ( ! $this -> isValidExportFormat ( $format )) {
return null ;
}
$formats = array (
'XML' => '.xml' ,
'CSV' => '.csv' ,
'JSON' => '.json' ,
'YAML' => '.yml' ,
);
return $formats [ $format ];
}
protected function getFormFilter ( $new = false )
{
2015-03-09 23:29:12 +01:00
$form = $this -> getConfiguration () -> getFormFilter () ? $this -> getConfiguration () -> getFormFilter () : $this -> getConfiguration () -> getFormNew ();
2015-03-02 21:57:49 +01:00
$form = $this -> createForm ( new $form ( $this -> getConfiguration () -> getFormFilterOptions ()));
if ( ! $new ) {
$datas = $this -> cleanFilterArray ( $this -> getSessionUser () -> getAttribute ( 'filter' , array (), $this -> getConfiguration () -> getStorageNamespace ()));
$form -> bind ( $datas );
}
return $form ;
}
protected function cleanFilterArray ( array $array )
{
foreach ( $array as $k => $v ) {
if ( trim ( $v ) === '' ) {
unset ( $array [ $k ]);
}
}
return $array ;
}
/**
* @ return mixed
* @ throws \LogicException
*/
public function getConfiguration ()
{
if ( empty ( $this -> configuration )) {
throw new \LogicException ( 'You must specify a crud configuration.' );
}
if ( null === $this -> configuration -> getStorageNamespace ()) {
$this -> configuration -> setStorageNamespace ( get_class ( $this ));
}
return $this -> configuration ;
}
/**
* @ Route ( " /jsTranslations.js " , name = " TrinityAdminBundle_jsTranslation " )
* @ Template ( " TrinityAdminBundle:BaseAdmin:jsTranslation.html.twig " )
*/
public function jsTranslationAction ( Request $request )
{
}
public function getUser ()
{
if ( ! $this -> container -> has ( 'security.context' )) {
throw new \LogicException ( 'The SecurityBundle is not registered in your application.' );
}
if ( null === $token = $this -> container -> get ( 'security.context' ) -> getToken ()) {
return null ;
}
if ( ! is_object ( $user = $token -> getUser ())) {
return null ;
}
if ( method_exists ( $user , 'setStorage' )) {
$user -> setStorage ( $this -> container -> get ( 'trinity.storage' ));
}
return $user ;
}
public function getSessionUser ()
{
return $this -> container -> get ( 'trinity.session_user' );
}
public function preSave ( $object )
{
}
public function postSave ( $object , $wasNew = false )
{
}
public function preRemove ( $object )
{
}
public function postRemove ( $object )
{
}
public function postDelete ( $object )
{
return $this -> postRemove ( $object );
}
public function preDelete ( $object )
{
return $this -> preRemove ( $object );
}
public function cleanString ( $text )
{
$text = preg_replace ( '`</?[^>]+>`U' , '' , $text );
$encoding = mb_detect_encoding ( $text );
$text = str_replace ( array ( ' ' , '’' ), ' ' , $text );
$text = html_entity_decode ( strip_tags ( $text ));
if ( $encoding != 'UTF-8' ) $text = utf8_encode ( $text );
$text = str_replace (
array (
'à' , 'â' , 'ä' , 'á' , 'ã' , 'å' ,
'î' , 'ï' , 'ì' , 'í' ,
'ô' , 'ö' , 'ò' , 'ó' , 'õ' , 'ø' ,
'ù' , 'û' , 'ü' , 'ú' ,
'é' , 'è' , 'ê' , 'ë' ,
'ç' , 'ÿ' , 'ñ' ,
'À' , 'Â' , 'Ä' , 'Á' , 'Ã' , 'Å' ,
'Î' , 'Ï' , 'Ì' , 'Í' ,
'Ô' , 'Ö' , 'Ò' , 'Ó' , 'Õ' , 'Ø' ,
'Ù' , 'Û' , 'Ü' , 'Ú' ,
'É' , 'È' , 'Ê' , 'Ë' ,
'Ç' , 'Ÿ' , 'Ñ' ,
'\'' , '"' ,
' ' , ' ' , ' ' , ' ' , ' '
),
array (
'a' , 'a' , 'a' , 'a' , 'a' , 'a' ,
'i' , 'i' , 'i' , 'i' ,
'o' , 'o' , 'o' , 'o' , 'o' , 'o' ,
'u' , 'u' , 'u' , 'u' ,
'e' , 'e' , 'e' , 'e' ,
'c' , 'y' , 'n' ,
'A' , 'A' , 'A' , 'A' , 'A' , 'A' ,
'I' , 'I' , 'I' , 'I' ,
'O' , 'O' , 'O' , 'O' , 'O' , 'O' ,
'U' , 'U' , 'U' , 'U' ,
'E' , 'E' , 'E' , 'E' ,
'C' , 'Y' , 'N' ,
' ' , ' ' ,
' ' , ' ' , ' ' , ' ' , ' '
), $text );
return strtolower ( $text );
}
}