idx
int64
0
60.3k
question
stringlengths
101
6.21k
target
stringlengths
7
803
50,100
private function _createSubscription ( array $ response ) { $ model = new Subscription ( ) ; $ model -> setId ( $ response [ 'id' ] ) ; $ model -> setOffer ( $ this -> _convertResponseToModel ( $ response [ 'offer' ] , 'offer' ) ) ; $ model -> setLivemode ( $ response [ 'livemode' ] ) ; $ model -> setTrialStart ( $ response [ 'trial_start' ] ) ; $ model -> setTrialEnd ( $ response [ 'trial_end' ] ) ; $ model -> setPeriodOfValidity ( $ response [ 'period_of_validity' ] ) ; $ model -> setEndOfPeriod ( $ response [ 'end_of_period' ] ) ; $ model -> setNextCaptureAt ( $ response [ 'next_capture_at' ] ) ; $ model -> setCreatedAt ( $ response [ 'created_at' ] ) ; $ model -> setUpdatedAt ( $ response [ 'updated_at' ] ) ; $ model -> setCanceledAt ( $ response [ 'canceled_at' ] ) ; $ model -> setPayment ( $ this -> _convertResponseToModel ( $ response [ 'payment' ] , "payment" ) ) ; $ model -> setClient ( $ this -> _convertResponseToModel ( $ response [ 'client' ] , "client" ) ) ; $ model -> setAppId ( $ response [ 'app_id' ] ) ; $ model -> setIsCanceled ( $ response [ 'is_canceled' ] ) ; $ model -> setIsDeleted ( $ response [ 'is_deleted' ] ) ; $ model -> setStatus ( $ response [ 'status' ] ) ; $ model -> setAmount ( $ response [ 'amount' ] ) ; $ model -> setTempAmount ( $ response [ 'temp_amount' ] ) ; return $ model ; }
Creates and fills a subscription model
50,101
private function _createWebhook ( array $ response ) { $ model = new Webhook ( ) ; $ model -> setId ( $ response [ 'id' ] ) ; isset ( $ response [ 'url' ] ) ? $ model -> setUrl ( $ response [ 'url' ] ) : $ model -> setEmail ( $ response [ 'email' ] ) ; $ model -> setLivemode ( $ response [ 'livemode' ] ) ; $ model -> setEventTypes ( $ response [ 'event_types' ] ) ; $ model -> setCreatedAt ( $ response [ 'created_at' ] ) ; $ model -> setUpdatedAt ( $ response [ 'updated_at' ] ) ; $ model -> setAppId ( $ response [ 'app_id' ] ) ; $ model -> setActive ( $ response [ 'active' ] ) ; return $ model ; }
Creates and fills a webhook model
50,102
private function _createFraud ( array $ response ) { $ model = new Fraud ( ) ; $ model -> setId ( $ response [ 'id' ] ) ; $ model -> setLivemode ( $ response [ 'livemode' ] ) ; $ model -> setStatus ( $ response [ 'status' ] ) ; $ model -> setCreatedAt ( $ response [ 'created_at' ] ) ; $ model -> setUpdatedAt ( $ response [ 'updated_at' ] ) ; return $ model ; }
Creates and fills a fraud model
50,103
private function _createChecksum ( array $ response ) { $ model = new Checksum ( ) ; $ model -> setId ( $ response [ 'id' ] ) ; $ model -> setChecksum ( $ response [ 'checksum' ] ) ; $ model -> setData ( $ response [ 'data' ] ) ; $ model -> setType ( $ response [ 'type' ] ) ; $ model -> setAction ( $ response [ 'action' ] ) ; $ model -> setAppId ( $ response [ 'app_id' ] ) ; $ model -> setCreatedAt ( $ response [ 'created_at' ] ) ; $ model -> setUpdatedAt ( $ response [ 'updated_at' ] ) ; return $ model ; }
Creates and fills a checksum model
50,104
private function _createItem ( array $ response ) { $ model = new Item ( ) ; $ model -> setName ( $ response [ Item :: FIELD_NAME ] ) -> setDescription ( $ response [ Item :: FIELD_DESCRIPTION ] ) -> setItemNumber ( $ response [ Item :: FIELD_ITEM_NUMBER ] ) -> setUrl ( $ response [ Item :: FIELD_URL ] ) -> setAmount ( $ response [ Item :: FIELD_AMOUNT ] ) -> setQuantity ( $ response [ Item :: FIELD_QUANTITY ] ) ; return $ model ; }
Creates and fills an item model .
50,105
private function _handleRecursive ( $ response , $ resourceName ) { $ result = null ; if ( isset ( $ response [ 'id' ] ) ) { $ result = $ this -> _convertResponseToModel ( $ response , $ resourceName ) ; } else if ( ! is_null ( $ response ) ) { $ paymentArray = array ( ) ; foreach ( $ response as $ paymentData ) { array_push ( $ paymentArray , $ this -> _convertResponseToModel ( $ paymentData , $ resourceName ) ) ; } $ result = $ paymentArray ; } return $ result ; }
Handles the multidimensional param arrays during model creation
50,106
public function convertErrorToModel ( array $ response , $ resourceName = null ) { $ errorModel = new Error ( ) ; $ httpStatusCode = isset ( $ response [ 'header' ] [ 'status' ] ) ? $ response [ 'header' ] [ 'status' ] : null ; $ errorModel -> setHttpStatusCode ( $ httpStatusCode ) ; $ responseCode = isset ( $ response [ 'body' ] [ 'data' ] [ 'response_code' ] ) ? $ response [ 'body' ] [ 'data' ] [ 'response_code' ] : null ; $ errorModel -> setResponseCode ( $ responseCode ) ; $ errorCode = 'Undefined Error. This should not happen!' ; $ rawError = array ( ) ; if ( isset ( $ this -> _errorCodes [ $ responseCode ] ) ) { $ errorCode = $ this -> _errorCodes [ $ responseCode ] ; } if ( isset ( $ resourceName ) && isset ( $ response [ 'body' ] [ 'data' ] ) ) { try { $ errorModel -> setRawObject ( $ this -> convertResponse ( $ response [ 'body' ] [ 'data' ] , $ resourceName ) ) ; } catch ( \ Exception $ e ) { } } if ( isset ( $ response [ 'body' ] ) ) { if ( is_array ( $ response [ 'body' ] ) ) { if ( isset ( $ response [ 'body' ] [ 'error' ] ) ) { $ rawError = $ response [ 'body' ] [ 'error' ] ; if ( is_array ( $ response [ 'body' ] [ 'error' ] ) ) { $ errorCode = $ this -> getErrorMessageFromArray ( $ response [ 'body' ] [ 'error' ] ) ; } elseif ( is_string ( $ response [ 'body' ] [ 'error' ] ) ) { $ errorCode = $ response [ 'body' ] [ 'error' ] ; } } } elseif ( is_string ( $ response [ 'body' ] ) ) { $ json = json_decode ( $ response [ 'body' ] , true ) ; if ( isset ( $ json [ 'error' ] ) ) { $ errorCode = $ json [ 'error' ] ; $ rawError = $ json [ 'error' ] ; } } } $ errorModel -> setErrorMessage ( $ errorCode ) ; $ errorModel -> setErrorResponseArray ( array ( 'error' => $ rawError ) ) ; return $ errorModel ; }
Generates an error model based on the provided response array
50,107
public function validateResponse ( array $ response ) { $ returnValue = false ; if ( isset ( $ response [ 'header' ] ) && isset ( $ response [ 'header' ] [ 'status' ] ) && $ response [ 'header' ] [ 'status' ] >= 200 && $ response [ 'header' ] [ 'status' ] < 300 ) { $ returnValue = true ; } return $ returnValue ; }
Validates the data responded by the API Just checks the header status is successful .
50,108
protected function cleanup ( $ dataType , $ data ) { if ( is_crud_translatable ( $ data ) ) { $ data -> deleteAttributeTranslations ( $ data -> getTranslatableAttributes ( ) ) ; } $ this -> deleteCrudImages ( $ data , $ dataType -> deleteRows -> where ( 'type' , 'image' ) ) ; foreach ( $ dataType -> deleteRows -> where ( 'type' , 'file' ) as $ row ) { $ files = json_decode ( $ data -> { $ row -> field } ) ; if ( $ files ) { foreach ( $ files as $ file ) { $ this -> deleteFileIfExists ( $ file -> download_link ) ; } } } }
Remove translations images and files related to a CRUD item .
50,109
public function deleteCrudImages ( $ data , $ rows ) { foreach ( $ rows as $ row ) { $ this -> deleteFileIfExists ( $ data -> { $ row -> field } ) ; $ options = json_decode ( $ row -> details ) ; if ( isset ( $ options -> thumbnails ) ) { foreach ( $ options -> thumbnails as $ thumbnail ) { $ ext = explode ( '.' , $ data -> { $ row -> field } ) ; $ extension = '.' . $ ext [ count ( $ ext ) - 1 ] ; $ path = str_replace ( $ extension , '' , $ data -> { $ row -> field } ) ; $ thumb_name = $ thumbnail -> name ; $ this -> deleteFileIfExists ( $ path . '-' . $ thumb_name . $ extension ) ; } } } if ( $ rows -> count ( ) > 0 ) { event ( new CrudImagesDeleted ( $ data , $ rows ) ) ; } }
Delete all images related to a CRUD item .
50,110
public function cropPhotos ( $ event ) { $ this -> filesystem = config ( 'admin.storage.disk' ) ; $ this -> folder = config ( 'admin.images.cropper.folder' ) . '/' . $ event -> slug ; $ this -> quality = config ( 'admin.images.cropper.quality' , 100 ) ; $ this -> request = $ event -> request ; $ this -> dataType = $ event -> dataType ; $ this -> model = $ event -> model ; $ cropperImages = $ this -> dataType -> rows ( ) -> whereType ( 'image' ) -> where ( 'details' , 'like' , '%cropper%' ) -> get ( ) ; foreach ( $ cropperImages as $ dataRow ) { $ details = json_decode ( $ dataRow -> details ) ; if ( ! isset ( $ details -> cropper ) ) { continue ; } if ( ! $ this -> request -> { $ dataRow -> field } ) { continue ; } $ this -> cropPhoto ( $ details -> cropper , $ dataRow ) ; } return true ; }
Save cropped photos .
50,111
private function cropPhoto ( $ cropper , $ dataRow ) { $ folder = $ this -> folder ; $ disk = Storage :: disk ( $ this -> filesystem ) ; if ( ! $ disk -> exists ( $ folder ) ) { $ disk -> makeDirectory ( $ folder ) ; } $ itemId = $ this -> model -> id ; foreach ( $ cropper as $ cropParam ) { $ inputName = $ dataRow -> field . '_' . $ cropParam -> name ; $ params = json_decode ( $ this -> request -> get ( $ inputName ) ) ; if ( ! is_object ( $ params ) ) { return false ; } $ imageName = $ this -> request -> { $ dataRow -> field } ; $ image = Image :: make ( $ disk -> path ( $ imageName ) ) ; $ image -> crop ( ( int ) $ params -> w , ( int ) $ params -> h , ( int ) $ params -> x , ( int ) $ params -> y ) ; $ image -> resize ( $ cropParam -> size -> width , $ cropParam -> size -> height ) ; $ photoName = $ folder . '/' . $ inputName . '_' . $ itemId . '_' . $ cropParam -> size -> name . '.' . $ image -> extension ; if ( isset ( $ cropParam -> watermark ) && file_exists ( $ cropParam -> watermark ) ) { $ watermark = Image :: make ( public_path ( ) . '/' . $ cropParam -> watermark ) ; $ watermark -> resize ( $ cropParam -> size -> width , null ) ; $ image -> insert ( $ watermark ) ; } $ image -> save ( $ disk -> path ( $ photoName ) , $ this -> quality ) ; if ( ! empty ( $ cropParam -> resize ) ) { foreach ( $ cropParam -> resize as $ cropParamResize ) { $ image -> resize ( $ cropParamResize -> width , $ cropParamResize -> height , function ( $ constraint ) { $ constraint -> aspectRatio ( ) ; } ) ; $ photoName = $ folder . '/' . $ inputName . '_' . $ itemId . '_' . $ cropParamResize -> name . '.' . $ image -> extension ; $ image -> save ( $ disk -> path ( $ photoName ) , $ this -> quality ) ; } } $ this -> model -> { $ dataRow -> field } = $ imageName ; $ this -> model -> save ( ) ; } }
Crop photo by coordinates .
50,112
public function getCroppedPhoto ( $ column , $ prefix , $ suffix ) { $ extension = 'jpeg' ; if ( isset ( $ this -> $ column ) ) { $ extension = pathinfo ( $ this -> $ column , PATHINFO_EXTENSION ) ? : $ extension ; } $ photoName = config ( 'admin.images.cropper.folder' ) . '/' . str_replace ( '_' , '-' , $ this -> getTable ( ) ) . '/' . $ column . '_' . $ prefix . '_' . $ this -> id . '_' . $ suffix . '.' . $ extension ; return Storage :: disk ( $ this -> filesystem ) -> url ( $ photoName ) ; }
Get the cropped photo url .
50,113
public function getLocation ( $ column ) { $ model = self :: select ( DB :: Raw ( 'ST_AsText(' . $ column . ') AS ' . $ column ) ) -> where ( 'id' , $ this -> id ) -> first ( ) ; return isset ( $ model ) ? $ model -> $ column : '' ; }
Get location as WKT from Geometry for given field .
50,114
protected function prepareOptions ( ) { if ( ! empty ( $ this -> configuration ) ) { if ( isset ( $ this -> configuration [ 'theme' ] ) ) { $ this -> theme = $ this -> configuration [ 'theme' ] ; } if ( isset ( $ this -> configuration [ 'modules' ] [ 'formula' ] ) ) { $ this -> _katex = true ; } if ( isset ( $ this -> configuration [ 'modules' ] [ 'syntax' ] ) ) { $ this -> _highlight = true ; } $ this -> _quillConfiguration = $ this -> configuration ; } else { if ( ! empty ( $ this -> theme ) ) { $ this -> _quillConfiguration [ 'theme' ] = $ this -> theme ; } if ( ! empty ( $ this -> bounds ) ) { $ this -> _quillConfiguration [ 'bounds' ] = new JsExpression ( $ this -> bounds ) ; } if ( ! empty ( $ this -> debug ) ) { $ this -> _quillConfiguration [ 'debug' ] = $ this -> debug ; } if ( ! empty ( $ this -> placeholder ) ) { $ this -> _quillConfiguration [ 'placeholder' ] = $ this -> placeholder ; } if ( ! empty ( $ this -> formats ) ) { $ this -> _quillConfiguration [ 'formates' ] = $ this -> formats ; } if ( ! empty ( $ this -> modules ) ) { foreach ( $ this -> modules as $ module => $ config ) { $ this -> _quillConfiguration [ 'modules' ] [ $ module ] = $ config ; if ( $ module === 'formula' ) { $ this -> _katex = true ; } if ( $ module === 'syntax' ) { $ this -> _highlight = true ; } } } if ( ! empty ( $ this -> toolbarOptions ) ) { $ this -> _quillConfiguration [ 'modules' ] [ 'toolbar' ] = $ this -> renderToolbar ( ) ; } } }
Prepares Quill configuration .
50,115
public function registerClientScript ( ) { $ view = $ this -> view ; if ( $ this -> _katex ) { $ katexAsset = KatexAsset :: register ( $ view ) ; $ katexAsset -> version = $ this -> katexVersion ; } if ( $ this -> _highlight ) { $ highlightAsset = HighlightAsset :: register ( $ view ) ; $ highlightAsset -> version = $ this -> highlightVersion ; $ highlightAsset -> style = $ this -> highlightStyle ; } $ asset = QuillAsset :: register ( $ view ) ; $ asset -> theme = $ this -> theme ; $ asset -> version = $ this -> quillVersion ; $ configs = Json :: encode ( $ this -> _quillConfiguration ) ; $ editor = 'q_' . preg_replace ( '~[^0-9_\p{L}]~u' , '_' , $ this -> id ) ; $ js = "var $editor=new Quill(\"#editor-{$this->id}\",$configs);" ; $ js .= "document.getElementById(\"editor-{$this->id}\").onclick=function(e){document.querySelector(\"#editor-{$this->id} .ql-editor\").focus();};" ; $ js .= "$editor.on('text-change',function(){document.getElementById(\"{$this->_fieldId}\").value=$editor.root.innerHTML;});" ; if ( ! empty ( $ this -> js ) ) { $ js .= str_replace ( '{quill}' , $ editor , $ this -> js ) ; } $ view -> registerJs ( $ js , View :: POS_END ) ; }
Registers widget assets . Note that Quill works without jQuery .
50,116
public function renderToolbar ( ) { if ( $ this -> toolbarOptions === self :: TOOLBAR_BASIC ) { return [ [ 'bold' , 'italic' , 'underline' , 'strike' , ] , [ [ 'list' => 'ordered' ] , [ 'list' => 'bullet' ] , ] , [ [ 'align' => [ ] ] , ] , [ 'link' , ] , ] ; } if ( $ this -> toolbarOptions === self :: TOOLBAR_FULL ) { return [ [ [ 'font' => [ ] ] , [ 'size' => [ 'small' , false , 'large' , 'huge' , ] , ] , ] , [ 'bold' , 'italic' , 'underline' , 'strike' , ] , [ [ 'color' => [ ] ] , [ 'background' => [ ] ] , ] , [ [ 'script' => 'sub' ] , [ 'script' => 'super' ] , ] , [ [ 'header' => 1 ] , [ 'header' => 2 ] , 'blockquote' , 'code-block' , ] , [ [ 'list' => 'ordered' ] , [ 'list' => 'bullet' ] , [ 'indent' => '-1' ] , [ 'indent' => '+1' ] , ] , [ [ 'direction' => 'rtl' ] , [ 'align' => [ ] ] , ] , [ 'link' , 'image' , 'video' , ] , [ 'clean' , ] , ] ; } return $ this -> toolbarOptions ; }
Prepares predefined set of buttons .
50,117
protected function getAdministratorRole ( ) { $ role = Admin :: model ( 'Role' ) -> firstOrNew ( [ 'name' => 'admin' , ] ) ; if ( ! $ role -> exists ) { $ role -> fill ( [ 'display_name' => 'Administrator' , ] ) -> save ( ) ; } return $ role ; }
Get the administrator role create it if it does not exists .
50,118
public static function display ( $ menuName , $ type = null , array $ options = [ ] ) { $ menu = static :: where ( 'name' , '=' , $ menuName ) -> with ( [ 'parent_items.children' => function ( $ q ) { $ q -> orderBy ( 'order' ) ; } ] ) -> first ( ) ; if ( ! isset ( $ menu ) ) { return false ; } event ( new MenuDisplay ( $ menu ) ) ; $ options = ( object ) $ options ; if ( in_array ( $ type , [ 'admin' , 'admin_menu' ] ) ) { $ permissions = Admin :: model ( 'Permission' ) -> all ( ) ; $ dataTypes = Admin :: model ( 'DataType' ) -> all ( ) ; $ prefix = trim ( route ( 'admin.dashboard' , [ ] , false ) , '/' ) ; $ user_permissions = null ; if ( ! Auth :: guest ( ) ) { $ user = Admin :: model ( 'User' ) -> find ( Auth :: id ( ) ) ; $ user_permissions = $ user -> role -> permissions -> pluck ( 'key' ) -> toArray ( ) ; } $ options -> user = ( object ) compact ( 'permissions' , 'dataTypes' , 'prefix' , 'user_permissions' ) ; $ type = 'admin::menu.' . $ type ; } else { if ( is_null ( $ type ) ) { $ type = 'admin::menu.default' ; } elseif ( $ type == 'bootstrap' && ! view ( ) -> exists ( $ type ) ) { $ type = 'admin::menu.bootstrap' ; } } if ( ! isset ( $ options -> locale ) ) { $ options -> locale = app ( ) -> getLocale ( ) ; } return new \ Illuminate \ Support \ HtmlString ( \ Illuminate \ Support \ Facades \ View :: make ( $ type , [ 'items' => $ menu -> parent_items -> sortBy ( 'order' ) , 'options' => $ options ] ) -> render ( ) ) ; }
Display menu .
50,119
public function thumbnail ( $ type ) { $ image = $ this -> attributes [ 'image' ] ; $ ext = pathinfo ( $ image , PATHINFO_EXTENSION ) ; $ name = rtrim ( $ image , '.' . $ ext ) ; return $ name . '-' . $ type . '.' . $ ext ; }
Method for returning specific thumbnail for post .
50,120
protected function registerAlertComponents ( ) { $ components = [ 'title' , 'text' , 'button' ] ; foreach ( $ components as $ component ) { $ class = 'LaravelAdminPanel\\Alert\\Components\\' . ucfirst ( camel_case ( $ component ) ) . 'Component' ; $ this -> app -> bind ( "admin.alert.components.{$component}" , $ class ) ; } }
Register alert components .
50,121
protected function registerWidgets ( ) { $ default_widgets = [ 'LaravelAdminPanel\\Widgets\\UserDimmer' , 'LaravelAdminPanel\\Widgets\\PostDimmer' , 'LaravelAdminPanel\\Widgets\\PageDimmer' ] ; $ widgets = config ( 'admin.dashboard.widgets' , $ default_widgets ) ; foreach ( $ widgets as $ widget ) { Widget :: group ( 'admin::dimmers' ) -> addWidget ( $ widget ) ; } }
Register widget .
50,122
public function handle ( CrudAdded $ crud ) { if ( config ( 'admin.add_crud_permission' ) && file_exists ( base_path ( 'routes/web.php' ) ) ) { $ role = Role :: where ( 'name' , 'admin' ) -> firstOrFail ( ) ; $ permissions = Permission :: where ( [ 'slug' => $ crud -> dataType -> slug ] ) -> get ( ) -> pluck ( 'id' ) -> all ( ) ; $ role -> permissions ( ) -> attach ( $ permissions ) ; } }
Create Permission for a given CRUD .
50,123
public function handle ( $ event ) { $ needCrop = $ event -> dataType -> rows ( ) -> whereType ( 'image' ) -> where ( 'details' , 'like' , '%cropper%' ) -> exists ( ) ; if ( $ needCrop ) { $ event -> model -> cropPhotos ( $ event ) ; } }
Crop the images for a given CRUD .
50,124
protected function generateContent ( $ stub , $ class ) { $ namespace = config ( 'admin.controllers.namespace' , 'LaravelAdminPanel\\Http\\Controllers' ) ; $ content = str_replace ( 'DummyNamespace' , $ namespace , $ stub ) ; $ content = str_replace ( 'FullBaseDummyClass' , 'LaravelAdminPanel\\Http\\Controllers\\' . $ class , $ content ) ; $ content = str_replace ( 'BaseDummyClass' , 'Base' . $ class , $ content ) ; $ content = str_replace ( 'DummyClass' , $ class , $ content ) ; return $ content ; }
Generate real content from stub .
50,125
public function delete_file_folder ( Request $ request ) { $ folderLocation = $ request -> folder_location ; $ fileFolder = $ request -> file_folder ; $ type = $ request -> type ; $ success = true ; $ error = '' ; if ( is_array ( $ folderLocation ) ) { $ folderLocation = rtrim ( implode ( '/' , $ folderLocation ) , '/' ) ; } $ location = "{$this->directory}/{$folderLocation}" ; $ fileFolder = "{$location}/{$fileFolder}" ; if ( $ type == 'folder' ) { if ( ! Storage :: disk ( $ this -> filesystem ) -> deleteDirectory ( $ fileFolder ) ) { $ error = __ ( 'admin.media.error_deleting_folder' ) ; $ success = false ; } } elseif ( ! Storage :: disk ( $ this -> filesystem ) -> delete ( $ fileFolder ) ) { $ error = __ ( 'admin.media.error_deleting_file' ) ; $ success = false ; } return compact ( 'success' , 'error' ) ; }
Delete File or Folder with 5 . 3
50,126
public function registerAssetFiles ( $ view ) { switch ( $ this -> theme ) { case Quill :: THEME_SNOW : $ this -> css = [ $ this -> url . $ this -> version . '/quill.snow.css' ] ; break ; case Quill :: THEME_BUBBLE : $ this -> css = [ $ this -> url . $ this -> version . '/quill.bubble.css' ] ; break ; default : $ this -> css = [ $ this -> url . $ this -> version . '/quill.core.css' ] ; } $ this -> js = [ $ this -> url . $ this -> version . '/quill.min.js' ] ; parent :: registerAssetFiles ( $ view ) ; }
Register CSS and JS file based on theme and version .
50,127
public function handle ( CrudAdded $ crud ) { if ( config ( 'admin.add_crud_menu_item' ) && file_exists ( base_path ( 'routes/web.php' ) ) ) { require base_path ( 'routes/web.php' ) ; $ menu = Menu :: where ( 'name' , 'admin' ) -> firstOrFail ( ) ; $ menuItem = MenuItem :: firstOrNew ( [ 'menu_id' => $ menu -> id , 'title' => $ crud -> dataType -> display_name_plural , 'url' => '/' . config ( 'admin.prefix' , 'admin' ) . '/' . $ crud -> dataType -> slug , ] ) ; $ order = Admin :: model ( 'MenuItem' ) -> highestOrderMenuItem ( ) ; if ( ! $ menuItem -> exists ) { $ menuItem -> fill ( [ 'target' => '_self' , 'icon_class' => $ crud -> dataType -> icon , 'color' => null , 'parent_id' => null , 'order' => $ order , ] ) -> save ( ) ; } } }
Create a MenuItem for a given CRUD .
50,128
public function sortByUrl ( ) { $ params = $ _GET ; $ isDesc = isset ( $ params [ 'sort_order' ] ) && $ params [ 'sort_order' ] != 'asc' ; if ( $ this -> isCurrentSortField ( ) && $ isDesc ) { $ params [ 'sort_order' ] = 'asc' ; } else { $ params [ 'sort_order' ] = 'desc' ; } $ params [ 'order_by' ] = $ this -> field ; return url ( ) -> current ( ) . '?' . http_build_query ( $ params ) ; }
Build the URL to sort data type by this field .
50,129
public function registerAssetFiles ( $ view ) { $ this -> css = [ $ this -> url . $ this -> version . '/styles/' . $ this -> style ] ; $ this -> js = [ $ this -> url . $ this -> version . '/highlight.min.js' ] ; parent :: registerAssetFiles ( $ view ) ; }
Register CSS and JS file based on version .
50,130
public function translations ( ) { return $ this -> hasMany ( Translation :: class , 'foreign_key' , $ this -> getKeyName ( ) ) -> where ( 'table_name' , $ this -> getTable ( ) ) -> whereIn ( 'locale' , config ( 'admin.multilingual.locales' , [ ] ) ) ; }
Load translations relation .
50,131
public function prepareTranslations ( & $ request ) { $ translations = [ ] ; $ transFields = $ this -> getTranslatableAttributes ( ) ; foreach ( $ transFields as $ field ) { $ trans = json_decode ( $ request -> input ( $ field . '_i18n' ) , true ) ; $ request -> merge ( [ $ field => $ trans [ config ( 'admin.multilingual.default' , 'en' ) ] ] ) ; $ translations [ $ field ] = $ this -> setAttributeTranslations ( $ field , $ trans ) ; unset ( $ request [ $ field . '_i18n' ] ) ; } unset ( $ request [ 'i18n_selector' ] ) ; return $ translations ; }
Prepare translations and set default locale field value .
50,132
public function apiUrl ( array $ query = [ ] ) { $ url = $ this -> _protocol ( ) . static :: API ; if ( $ this -> _runtimeConfig [ 'map' ] [ 'api' ] ) { $ query [ 'v' ] = $ this -> _runtimeConfig [ 'map' ] [ 'api' ] ; } if ( $ this -> _runtimeConfig [ 'key' ] ) { $ query [ 'key' ] = $ this -> _runtimeConfig [ 'key' ] ; } if ( $ this -> _runtimeConfig [ 'language' ] ) { $ query [ 'language' ] = $ this -> _runtimeConfig [ 'language' ] ; } if ( $ query ) { $ query = http_build_query ( $ query ) ; $ url .= '?' . $ query ; } return $ url ; }
JS maps . google API url .
50,133
public function reset ( $ full = true ) { static :: $ markerCount = static :: $ infoWindowCount = 0 ; $ this -> markers = $ this -> infoWindows = [ ] ; if ( $ full ) { $ this -> _runtimeConfig = $ this -> _config ; } }
Make it possible to include multiple maps per page resets markers infoWindows etc
50,134
public function setControls ( array $ options = [ ] ) { if ( isset ( $ options [ 'streetView' ] ) ) { $ this -> _runtimeConfig [ 'map' ] [ 'streetViewControl' ] = $ options [ 'streetView' ] ; } if ( isset ( $ options [ 'zoom' ] ) ) { $ this -> _runtimeConfig [ 'map' ] [ 'scaleControl' ] = $ options [ 'zoom' ] ; } if ( isset ( $ options [ 'scrollwheel' ] ) ) { $ this -> _runtimeConfig [ 'map' ] [ 'scrollwheel' ] = $ options [ 'scrollwheel' ] ; } if ( isset ( $ options [ 'keyboardShortcuts' ] ) ) { $ this -> _runtimeConfig [ 'map' ] [ 'keyboardShortcuts' ] = $ options [ 'keyboardShortcuts' ] ; } if ( isset ( $ options [ 'type' ] ) ) { $ this -> _runtimeConfig [ 'map' ] [ 'type' ] = $ options [ 'type' ] ; } }
Set the controls of current map
50,135
protected function _initialLocation ( ) { if ( $ this -> _runtimeConfig [ 'map' ] [ 'lat' ] && $ this -> _runtimeConfig [ 'map' ] [ 'lng' ] ) { return 'new google.maps.LatLng(' . $ this -> _runtimeConfig [ 'map' ] [ 'lat' ] . ', ' . $ this -> _runtimeConfig [ 'map' ] [ 'lng' ] . ')' ; } $ this -> _runtimeConfig [ 'autoCenter' ] = true ; return 'false' ; }
Generate a new LatLng object with the current lat and lng .
50,136
public function iconSet ( $ color , $ char = null , $ size = 'm' ) { $ colors = [ 'red' , 'green' , 'yellow' , 'blue' , 'purple' , 'white' , 'black' ] ; if ( ! in_array ( $ color , $ colors ) ) { $ color = 'red' ; } if ( ! empty ( $ this -> _runtimeConfig [ 'localImages' ] ) ) { $ this -> setIcons [ 'color' ] = $ this -> _runtimeConfig [ 'localImages' ] . 'marker%s.png' ; $ this -> setIcons [ 'alpha' ] = $ this -> _runtimeConfig [ 'localImages' ] . 'marker%s%s.png' ; $ this -> setIcons [ 'numeric' ] = $ this -> _runtimeConfig [ 'localImages' ] . '%s%s.png' ; $ this -> setIcons [ 'special' ] = $ this -> _runtimeConfig [ 'localImages' ] . '%s.png' ; } if ( ! empty ( $ char ) ) { if ( $ color === 'red' ) { $ color = '' ; } else { $ color = '_' . $ color ; } $ url = sprintf ( $ this -> setIcons [ 'alpha' ] , $ color , $ char ) ; } else { if ( $ color === 'red' ) { $ color = '' ; } else { $ color = '_' . $ color ; } $ url = sprintf ( $ this -> setIcons [ 'color' ] , $ color ) ; } $ shadow = 'https://www.google.com/mapfiles/shadow50.png' ; $ res = [ 'url' => $ url , 'icon' => $ this -> icon ( $ url , [ 'size' => [ 'width' => 20 , 'height' => 34 ] ] ) , 'shadow' => $ this -> icon ( $ shadow , [ 'size' => [ 'width' => 37 , 'height' => 34 ] , 'shadow' => [ 'width' => 10 , 'height' => 34 ] ] ) ] ; return $ res ; }
Get a custom icon set
50,137
public function addIcon ( $ image , $ shadow = null , array $ imageOptions = [ ] , array $ shadowOptions = [ ] ) { $ res = [ 'url' => $ image ] ; $ res [ 'icon' ] = $ this -> icon ( $ image , $ imageOptions ) ; if ( $ shadow ) { $ last = $ this -> _iconRemember [ $ res [ 'icon' ] ] ; if ( ! isset ( $ shadowOptions [ 'anchor' ] ) ) { $ shadowOptions [ 'anchor' ] = [ ] ; } $ shadowOptions [ 'anchor' ] = $ last [ 'options' ] [ 'anchor' ] + $ shadowOptions [ 'anchor' ] ; $ res [ 'shadow' ] = $ this -> icon ( $ shadow , $ shadowOptions ) ; } return $ res ; }
Generate icon array .
50,138
public function icon ( $ url , array $ options = [ ] ) { if ( empty ( $ options [ 'size' ] ) ) { $ path = $ url ; if ( ! preg_match ( '#^((https?://)|//)#i' , $ path ) ) { $ path = WWW_ROOT . ltrim ( $ url , '/' ) ; } $ data = getimagesize ( $ path ) ; if ( $ data ) { $ options [ 'size' ] [ 'width' ] = $ data [ 0 ] ; $ options [ 'size' ] [ 'height' ] = $ data [ 1 ] ; } else { $ options [ 'size' ] [ 'width' ] = $ options [ 'size' ] [ 'height' ] = 0 ; } } if ( empty ( $ options [ 'anchor' ] ) ) { $ options [ 'anchor' ] [ 'width' ] = ( int ) ( $ options [ 'size' ] [ 'width' ] / 2 ) ; $ options [ 'anchor' ] [ 'height' ] = $ options [ 'size' ] [ 'height' ] ; } if ( empty ( $ options [ 'origin' ] ) ) { $ options [ 'origin' ] [ 'width' ] = $ options [ 'origin' ] [ 'height' ] = 0 ; } if ( isset ( $ options [ 'shadow' ] ) ) { $ options [ 'anchor' ] = $ options [ 'shadow' ] ; } $ icon = 'new google.maps.MarkerImage("' . $ url . '", new google.maps.Size(' . $ options [ 'size' ] [ 'width' ] . ', ' . $ options [ 'size' ] [ 'height' ] . '), new google.maps.Point(' . $ options [ 'origin' ] [ 'width' ] . ', ' . $ options [ 'origin' ] [ 'height' ] . '), new google.maps.Point(' . $ options [ 'anchor' ] [ 'width' ] . ', ' . $ options [ 'anchor' ] [ 'height' ] . '))' ; $ this -> icons [ static :: $ iconCount ] = $ icon ; $ this -> _iconRemember [ static :: $ iconCount ] = [ 'url' => $ url , 'options' => $ options , 'id' => static :: $ iconCount ] ; return static :: $ iconCount ++ ; }
Generate icon object
50,139
public function addInfoWindow ( array $ options = [ ] ) { $ defaults = $ this -> _runtimeConfig [ 'infoWindow' ] ; $ options += $ defaults ; if ( ! empty ( $ options [ 'lat' ] ) && ! empty ( $ options [ 'lng' ] ) ) { $ position = 'new google.maps.LatLng(' . $ options [ 'lat' ] . ', ' . $ options [ 'lng' ] . ')' ; } else { $ position = ' ' . $ this -> name ( ) . ' .getCenter()' ; } $ windows = " gInfoWindows" . static :: $ mapCount . ".push(new google.maps.InfoWindow({ position: {$position}, content: " . $ this -> escapeString ( $ options [ 'content' ] ) . ", maxWidth: {$options['maxWidth']}, pixelOffset: {$options['pixelOffset']} /*zIndex: {$options['zIndex']},*/ })); " ; $ this -> map .= $ windows ; return static :: $ infoWindowCount ++ ; }
Creates a new InfoWindow .
50,140
public function addEvent ( $ marker , $ infoWindow , $ open = false ) { $ this -> map .= " google.maps.event.addListener(gMarkers" . static :: $ mapCount . "[{$marker}], 'click', function() { gInfoWindows" . static :: $ mapCount . "[$infoWindow].open(" . $ this -> name ( ) . ", this); }); " ; if ( $ open ) { $ event = 'gInfoWindows' . static :: $ mapCount . "[$infoWindow].open(" . $ this -> name ( ) . ', gMarkers' . static :: $ mapCount . '[' . $ marker . ']);' ; $ this -> addCustom ( $ event ) ; } }
Add event to open marker on click .
50,141
public function addDirections ( $ from , $ to , array $ options = [ ] ) { $ id = 'd' . static :: $ markerCount ++ ; $ defaults = $ this -> _runtimeConfig [ 'directions' ] ; $ options += $ defaults ; $ travelMode = $ this -> travelModes [ $ options [ 'travelMode' ] ] ; $ directions = " var {$id}Service = new google.maps.DirectionsService(); var {$id}Display; {$id}Display = new google.maps.DirectionsRenderer(); {$id}Display. setMap(" . $ this -> name ( ) . "); " ; if ( ! empty ( $ options [ 'directionsDiv' ] ) ) { $ directions .= "{$id}Display. setPanel(document.getElementById('" . $ options [ 'directionsDiv' ] . "'));" ; } if ( is_array ( $ from ) ) { $ from = 'new google.maps.LatLng(' . ( float ) $ from [ 'lat' ] . ', ' . ( float ) $ from [ 'lng' ] . ')' ; } else { $ from = '"' . h ( $ from ) . '"' ; } if ( is_array ( $ to ) ) { $ to = 'new google.maps.LatLng(' . ( float ) $ to [ 'lat' ] . ', ' . ( float ) $ to [ 'lng' ] . ')' ; } else { $ to = '"' . h ( $ to ) . '"' ; } $ directions .= " var request = { origin: $from, destination: $to, unitSystem: google.maps.UnitSystem." . $ options [ 'unitSystem' ] . ", travelMode: google.maps.TravelMode. $travelMode }; {$id}Service.route(request, function(result, status) { if (status == google.maps.DirectionsStatus.OK) { {$id}Display. setDirections(result); } }); " ; $ this -> map .= $ directions ; }
Add directions to the map .
50,142
public function addPolyline ( $ from , $ to , array $ options = [ ] ) { if ( is_array ( $ from ) ) { $ from = 'new google.maps.LatLng(' . ( float ) $ from [ 'lat' ] . ', ' . ( float ) $ from [ 'lng' ] . ')' ; } else { throw new Exception ( 'not implemented yet, use array of lat/lng' ) ; } if ( is_array ( $ to ) ) { $ to = 'new google.maps.LatLng(' . ( float ) $ to [ 'lat' ] . ', ' . ( float ) $ to [ 'lng' ] . ')' ; } else { throw new Exception ( 'not implemented yet, use array of lat/lng' ) ; } $ defaults = $ this -> _runtimeConfig [ 'polyline' ] ; $ options += $ defaults ; $ id = 'p' . static :: $ markerCount ++ ; $ polyline = "var start = $from;" ; $ polyline .= "var end = $to;" ; $ polyline .= " var poly = [ start, end ]; var {$id}Polyline = new google.maps.Polyline({ path: poly, strokeColor: '" . $ options [ 'color' ] . "', strokeOpacity: " . $ options [ 'opacity' ] . ", strokeWeight: " . $ options [ 'weight' ] . " }); {$id}Polyline.setMap(" . $ this -> name ( ) . "); " ; $ this -> map .= $ polyline ; }
Add a polyline
50,143
public function finalize ( $ return = false ) { $ script = $ this -> _arrayToObject ( 'matching' , $ this -> matching , false , true ) . PHP_EOL ; $ script .= $ this -> _arrayToObject ( 'gIcons' . static :: $ mapCount , $ this -> icons , false , false ) . ' jQuery(document).ready(function() { ' ; $ script .= $ this -> map ; if ( $ this -> _runtimeConfig [ 'geolocate' ] ) { $ script .= $ this -> _geolocate ( ) ; } if ( $ this -> _runtimeConfig [ 'showMarker' ] && ! empty ( $ this -> markers ) && is_array ( $ this -> markers ) ) { $ script .= implode ( $ this -> markers , ' ' ) ; } if ( $ this -> _runtimeConfig [ 'autoCenter' ] ) { $ script .= $ this -> _autoCenter ( ) ; } $ script .= ' });' ; static :: $ mapCount ++ ; if ( $ return ) { return $ script ; } $ this -> Html -> scriptBlock ( $ script , [ 'block' => true ] ) ; }
Finalize the map and write the javascript to the buffer . Make sure that your view does also output the buffer at some place!
50,144
public function geolocateCallback ( $ js ) { if ( $ js === false ) { $ this -> _runtimeConfig [ 'callbacks' ] [ 'geolocate' ] = false ; return ; } $ this -> _runtimeConfig [ 'callbacks' ] [ 'geolocate' ] = $ js ; }
Set a custom geolocate callback
50,145
public function mapLink ( $ title , $ mapOptions = [ ] , $ linkOptions = [ ] ) { return $ this -> Html -> link ( $ title , $ this -> mapUrl ( $ mapOptions + [ 'escape' => false ] ) , $ linkOptions ) ; }
Returns a maps . google link
50,146
public function mapUrl ( array $ options = [ ] ) { $ url = $ this -> _protocol ( ) . 'maps.google.com/maps?' ; $ urlArray = ! empty ( $ options [ 'query' ] ) ? $ options [ 'query' ] : [ ] ; if ( ! empty ( $ options [ 'from' ] ) ) { $ urlArray [ 'saddr' ] = $ options [ 'from' ] ; } if ( ! empty ( $ options [ 'to' ] ) && is_array ( $ options [ 'to' ] ) ) { $ to = array_shift ( $ options [ 'to' ] ) ; foreach ( $ options [ 'to' ] as $ key => $ value ) { $ to .= '+to:' . $ value ; } $ urlArray [ 'daddr' ] = $ to ; } elseif ( ! empty ( $ options [ 'to' ] ) ) { $ urlArray [ 'daddr' ] = $ options [ 'to' ] ; } if ( isset ( $ options [ 'zoom' ] ) && $ options [ 'zoom' ] !== false ) { $ urlArray [ 'z' ] = ( int ) $ options [ 'zoom' ] ; } $ options += [ 'escape' => true , ] ; $ query = http_build_query ( $ urlArray ) ; if ( $ options [ 'escape' ] ) { $ query = h ( $ query ) ; } return $ url . $ query ; }
Returns a maps . google url
50,147
public function staticMap ( array $ options = [ ] , array $ attributes = [ ] ) { $ defaultAttributes = [ 'alt' => __d ( 'tools' , 'Map' ) ] ; $ attributes += $ defaultAttributes ; $ escape = version_compare ( Configure :: version ( ) , '3.5.1' ) < 0 ? true : false ; return $ this -> Html -> image ( $ this -> staticMapUrl ( $ options + [ 'escape' => $ escape ] ) , $ attributes ) ; }
Creates a plain image map .
50,148
public function staticMapLink ( $ title , array $ mapOptions = [ ] , array $ linkOptions = [ ] ) { return $ this -> Html -> link ( $ title , $ this -> staticMapUrl ( $ mapOptions + [ 'escape' => false ] ) , $ linkOptions ) ; }
Create a link to a plain image map
50,149
public function staticPaths ( array $ pos = [ ] ) { $ defaults = [ 'color' => 'blue' , 'weight' => 5 ] ; if ( ! isset ( $ pos [ 0 ] ) ) { $ pos = [ $ pos ] ; } $ res = [ ] ; foreach ( $ pos as $ p ) { $ options = $ p + $ defaults ; $ markers = $ options [ 'path' ] ; unset ( $ options [ 'path' ] ) ; if ( ! empty ( $ options [ 'color' ] ) ) { $ options [ 'color' ] = $ this -> _prepColor ( $ options [ 'color' ] ) ; } $ path = [ ] ; foreach ( $ options as $ key => $ value ) { $ path [ ] = $ key . ':' . urlencode ( $ value ) ; } foreach ( $ markers as $ key => $ pos ) { if ( is_array ( $ pos ) ) { $ pos = $ pos [ 'lat' ] . ',' . $ pos [ 'lng' ] ; } $ path [ ] = $ pos ; } $ res [ ] = implode ( '|' , $ path ) ; } return $ res ; }
Prepare paths for staticMap
50,150
public function staticMarkers ( array $ pos = [ ] , array $ style = [ ] ) { $ markers = [ ] ; $ verbose = false ; $ defaults = [ 'shadow' => 'true' , 'color' => 'blue' , 'label' => '' , 'address' => '' , 'size' => '' ] ; if ( ! isset ( $ pos [ 0 ] ) ) { $ pos = [ $ pos ] ; } foreach ( $ pos as $ p ) { $ p += $ style + $ defaults ; if ( ! empty ( $ p [ 'lat' ] ) && ! empty ( $ p [ 'lng' ] ) ) { $ p [ 'address' ] = $ p [ 'lat' ] . ',' . $ p [ 'lng' ] ; } $ p [ 'address' ] = urlencode ( $ p [ 'address' ] ) ; $ values = [ ] ; if ( ! empty ( $ p [ 'color' ] ) ) { $ p [ 'color' ] = $ this -> _prepColor ( $ p [ 'color' ] ) ; $ values [ ] = 'color:' . $ p [ 'color' ] ; } if ( ! empty ( $ p [ 'label' ] ) ) { $ values [ ] = 'label:' . strtoupper ( $ p [ 'label' ] ) ; } if ( ! empty ( $ p [ 'size' ] ) ) { $ values [ ] = 'size:' . $ p [ 'size' ] ; } if ( ! empty ( $ p [ 'shadow' ] ) ) { $ values [ ] = 'shadow:' . $ p [ 'shadow' ] ; } if ( ! empty ( $ p [ 'icon' ] ) ) { $ values [ ] = 'icon:' . urlencode ( $ p [ 'icon' ] ) ; } $ values [ ] = $ p [ 'address' ] ; $ markers [ ] = implode ( '|' , $ values ) ; } if ( $ verbose ) { } return $ markers ; }
Prepare markers for staticMap
50,151
protected function _protocol ( ) { $ https = $ this -> _runtimeConfig [ 'https' ] ; if ( $ https === null ) { $ https = ! empty ( $ _SERVER [ 'HTTPS' ] ) && $ _SERVER [ 'HTTPS' ] === 'on' ; } return $ https ? 'https://' : '//' ; }
Ensure that we stay on the appropriate protocol
50,152
public function findDistance ( Query $ query , array $ options ) { $ options += [ 'tableName' => null , 'sort' => true ] ; $ sql = $ this -> distanceExpr ( $ options [ 'lat' ] , $ options [ 'lng' ] , null , null , $ options [ 'tableName' ] ) ; if ( $ query -> autoFields ( ) === null ) { $ query -> autoFields ( true ) ; } $ query -> select ( [ 'distance' => $ query -> newExpr ( $ sql ) ] ) ; if ( isset ( $ options [ 'distance' ] ) ) { $ query -> where ( function ( $ exp ) use ( $ sql , $ options ) { return $ exp -> lt ( $ sql , $ options [ 'distance' ] ) ; } ) ; } if ( $ options [ 'sort' ] ) { $ sort = $ options [ 'sort' ] === true ? 'ASC' : $ options [ 'sort' ] ; $ query -> order ( [ 'distance' => $ sort ] ) ; } return $ query ; }
Custom finder for distance .
50,153
protected function _execute ( $ address ) { $ GeocodedAddresses = null ; if ( $ this -> getConfig ( 'cache' ) ) { $ GeocodedAddresses = TableRegistry :: get ( 'Geo.GeocodedAddresses' ) ; $ result = $ GeocodedAddresses -> find ( ) -> where ( [ 'address' => $ address ] ) -> first ( ) ; if ( $ result ) { $ data = $ result -> data ; return $ data ? : null ; } } try { $ addresses = $ this -> _Geocoder -> geocode ( $ address ) ; } catch ( InconclusiveException $ e ) { $ addresses = null ; } catch ( NotAccurateEnoughException $ e ) { $ addresses = null ; } $ result = null ; if ( $ addresses && $ addresses -> count ( ) > 0 ) { $ result = $ addresses -> first ( ) ; } if ( $ this -> getConfig ( 'cache' ) ) { $ addressEntity = $ GeocodedAddresses -> newEntity ( [ 'address' => $ address ] ) ; if ( $ result ) { $ formatter = new StringFormatter ( ) ; $ addressEntity -> formatted_address = $ formatter -> format ( $ result , '%S %n, %z %L' ) ; $ addressEntity -> lat = $ result -> getLatitude ( ) ; $ addressEntity -> lng = $ result -> getLongitude ( ) ; $ addressEntity -> country = $ result -> getCountry ( ) -> getCode ( ) ; $ addressEntity -> data = $ result ; } if ( ! $ GeocodedAddresses -> save ( $ addressEntity , [ 'atomic' => false ] ) ) { throw new RuntimeException ( 'Could not store geocoding cache data' ) ; } } return $ result ; }
Uses the Geocode class to query
50,154
protected function _calculationValue ( $ unit ) { if ( ! isset ( $ this -> _Calculator ) ) { $ this -> _Calculator = new Calculator ( ) ; } return $ this -> _Calculator -> convert ( 6371.04 , Calculator :: UNIT_KM , $ unit ) ; }
Get the current unit factor
50,155
public function isExpectedType ( Address $ address ) { $ expected = $ this -> _config [ 'expect' ] ; if ( ! $ expected ) { return true ; } $ adminLevels = $ address -> getAdminLevels ( ) ; $ map = [ static :: TYPE_AAL1 => 1 , static :: TYPE_AAL2 => 2 , static :: TYPE_AAL3 => 3 , static :: TYPE_AAL4 => 4 , static :: TYPE_AAL5 => 5 , ] ; foreach ( $ expected as $ expect ) { switch ( $ expect ) { case static :: TYPE_COUNTRY : if ( $ address -> getCountry ( ) !== null ) { return true ; } break ; case ( static :: TYPE_AAL1 ) : case ( static :: TYPE_AAL2 ) : case ( static :: TYPE_AAL3 ) : case ( static :: TYPE_AAL4 ) : case ( static :: TYPE_AAL5 ) : if ( $ adminLevels -> has ( $ map [ $ expect ] ) ) { return true ; } break ; case static :: TYPE_LOC : if ( $ address -> getLocality ( ) !== null ) { return true ; } break ; case static :: TYPE_SUBLOC : if ( $ address -> getSubLocality ( ) !== null ) { return true ; } break ; case static :: TYPE_POSTAL : if ( $ address -> getPostalCode ( ) !== null ) { return true ; } break ; case static :: TYPE_ADDRESS : if ( $ address -> getStreetName ( ) !== null ) { return true ; } break ; case static :: TYPE_NUMBER : if ( $ address -> getStreetNumber ( ) !== null ) { return true ; } break ; } } return false ; }
Expects certain address types to be present in the given address .
50,156
public function convert ( $ value , $ fromUnit , $ toUnit ) { $ fromUnit = strtoupper ( $ fromUnit ) ; $ toUnit = strtoupper ( $ toUnit ) ; if ( ! isset ( $ this -> _units [ $ fromUnit ] ) || ! isset ( $ this -> _units [ $ toUnit ] ) ) { throw new CalculatorException ( 'Invalid Unit' ) ; } if ( $ fromUnit === static :: UNIT_MILES ) { $ value *= $ this -> _units [ $ toUnit ] ; } elseif ( $ toUnit === static :: UNIT_MILES ) { $ value /= $ this -> _units [ $ fromUnit ] ; } else { $ value /= $ this -> _units [ $ fromUnit ] ; $ value *= $ this -> _units [ $ toUnit ] ; } return $ value ; }
Convert between units
50,157
public function value ( $ val = [ ] , $ quoteString = null , $ key = 'value' ) { if ( $ quoteString === null ) { $ quoteString = true ; } switch ( true ) { case ( is_array ( $ val ) || is_object ( $ val ) ) : $ val = $ this -> object ( $ val ) ; break ; case ( $ val === null ) : $ val = 'null' ; break ; case ( is_bool ( $ val ) ) : $ val = ( $ val === true ) ? 'true' : 'false' ; break ; case ( is_int ( $ val ) ) : break ; case ( is_float ( $ val ) ) : $ val = sprintf ( '%.11f' , $ val ) ; break ; default : $ val = $ this -> escape ( $ val ) ; if ( $ quoteString ) { $ val = '"' . $ val . '"' ; } } return $ val ; }
Converts a PHP - native variable of any type to a JSON - equivalent representation
50,158
protected function _processOptions ( $ method , $ options ) { $ options = $ this -> _mapOptions ( ) ; $ options = $ this -> _prepareCallbacks ( $ method , $ options ) ; $ options = $ this -> _parseOptions ( $ options , array_keys ( $ this -> _callbackArguments [ $ method ] ) ) ; return $ options ; }
Convenience wrapper method for all common option processing steps . Runs _mapOptions _prepareCallbacks and _parseOptions in order .
50,159
protected function _toQuerystring ( $ parameters ) { $ out = '' ; $ keys = array_keys ( $ parameters ) ; $ count = count ( $ parameters ) ; for ( $ i = 0 ; $ i < $ count ; $ i ++ ) { $ out .= $ keys [ $ i ] . '=' . $ parameters [ $ keys [ $ i ] ] ; if ( $ i < $ count - 1 ) { $ out .= '&' ; } } return $ out ; }
Convert an array of data into a query string
50,160
protected static function utf8 ( $ string ) { $ map = [ ] ; $ values = [ ] ; $ find = 1 ; $ length = strlen ( $ string ) ; for ( $ i = 0 ; $ i < $ length ; $ i ++ ) { $ value = ord ( $ string [ $ i ] ) ; if ( $ value < 128 ) { $ map [ ] = $ value ; } else { if ( empty ( $ values ) ) { $ find = ( $ value < 224 ) ? 2 : 3 ; } $ values [ ] = $ value ; if ( count ( $ values ) === $ find ) { if ( $ find == 3 ) { $ map [ ] = ( ( $ values [ 0 ] % 16 ) * 4096 ) + ( ( $ values [ 1 ] % 64 ) * 64 ) + ( $ values [ 2 ] % 64 ) ; } else { $ map [ ] = ( ( $ values [ 0 ] % 32 ) * 64 ) + ( $ values [ 1 ] % 64 ) ; } $ values = [ ] ; $ find = 1 ; } } } return $ map ; }
Converts a multibyte character string to the decimal value of the character
50,161
protected function parseGet ( $ url , $ query ) { $ append = strpos ( $ url , '?' ) === false ? '?' : '&' ; return $ url . $ append . http_build_query ( $ query ) ; }
Appends query array onto URL
50,162
protected function request ( $ url , $ parameters = array ( ) , $ request = false ) { $ this -> lastRequest = $ url ; $ this -> lastRequestData = $ parameters ; $ this -> responseHeaders = array ( ) ; $ curl = curl_init ( $ url ) ; $ curlOptions = array ( CURLOPT_SSL_VERIFYPEER => false , CURLOPT_REFERER => $ url , CURLOPT_RETURNTRANSFER => true , CURLOPT_HEADERFUNCTION => array ( $ this , 'parseHeader' ) , ) ; if ( ! empty ( $ parameters ) || ! empty ( $ request ) ) { if ( ! empty ( $ request ) ) { $ curlOptions [ CURLOPT_CUSTOMREQUEST ] = $ request ; $ parameters = http_build_query ( $ parameters ) ; } else { $ curlOptions [ CURLOPT_POST ] = true ; } $ curlOptions [ CURLOPT_POSTFIELDS ] = $ parameters ; } curl_setopt_array ( $ curl , $ curlOptions ) ; $ response = curl_exec ( $ curl ) ; $ error = curl_error ( $ curl ) ; $ this -> lastRequestInfo = curl_getinfo ( $ curl ) ; curl_close ( $ curl ) ; if ( ! empty ( $ error ) ) { throw new \ Exception ( $ error ) ; } return $ this -> parseResponse ( $ response ) ; }
Makes HTTP Request to the API
50,163
public function authenticationUrl ( $ redirect , $ approvalPrompt = 'auto' , $ scope = null , $ state = null ) { $ parameters = array ( 'client_id' => $ this -> clientId , 'redirect_uri' => $ redirect , 'response_type' => 'code' , 'approval_prompt' => $ approvalPrompt , 'state' => $ state , ) ; if ( ! is_null ( $ scope ) ) { $ parameters [ 'scope' ] = $ scope ; } return $ this -> parseGet ( $ this -> authUrl . 'authorize' , $ parameters ) ; }
Creates authentication URL for your app
50,164
public function tokenExchange ( $ code ) { $ parameters = array ( 'client_id' => $ this -> clientId , 'client_secret' => $ this -> clientSecret , 'code' => $ code , ) ; return $ this -> request ( $ this -> authUrl . 'token' , $ parameters ) ; }
Authenticates token returned from API
50,165
public function get ( $ request , $ parameters = array ( ) ) { $ parameters = $ this -> generateParameters ( $ parameters ) ; $ requestUrl = $ this -> parseGet ( $ this -> getAbsoluteUrl ( $ request ) , $ parameters ) ; return $ this -> request ( $ requestUrl ) ; }
Sends GET request to specified API endpoint
50,166
public function put ( $ request , $ parameters = array ( ) ) { return $ this -> request ( $ this -> getAbsoluteUrl ( $ request ) , $ this -> generateParameters ( $ parameters ) , 'PUT' ) ; }
Sends PUT request to specified API endpoint
50,167
public function post ( $ request , $ parameters = array ( ) ) { return $ this -> request ( $ this -> getAbsoluteUrl ( $ request ) , $ this -> generateParameters ( $ parameters ) ) ; }
Sends POST request to specified API endpoint
50,168
public function delete ( $ request , $ parameters = array ( ) ) { return $ this -> request ( $ this -> getAbsoluteUrl ( $ request ) , $ this -> generateParameters ( $ parameters ) , 'DELETE' ) ; }
Sends DELETE request to specified API endpoint
50,169
protected function getAbsoluteUrl ( $ request ) { $ request = ltrim ( $ request ) ; if ( strpos ( $ request , 'http' ) === 0 ) { return $ request ; } return $ this -> apiUrl . $ request ; }
Checks the given request string and returns the absolute URL to make the necessary API call
50,170
private function getClasses ( $ directory ) { $ classes = [ ] ; $ directoryList = [ ] ; $ includedFiles = [ ] ; $ finder = new Finder ( ) ; try { $ finder -> in ( $ directory ) -> files ( ) -> name ( '*.php' ) ; } catch ( \ InvalidArgumentException $ e ) { return [ [ ] , [ ] ] ; } foreach ( $ finder as $ file ) { $ directoryList [ $ file -> getPath ( ) ] = true ; $ sourceFile = $ file -> getRealpath ( ) ; if ( ! preg_match ( '(^phar:)i' , $ sourceFile ) ) { $ sourceFile = realpath ( $ sourceFile ) ; } require_once $ sourceFile ; $ includedFiles [ $ sourceFile ] = true ; } $ declared = get_declared_classes ( ) ; foreach ( $ declared as $ className ) { $ reflectionClass = new \ ReflectionClass ( $ className ) ; $ sourceFile = $ reflectionClass -> getFileName ( ) ; if ( $ reflectionClass -> isAbstract ( ) ) { continue ; } if ( method_exists ( $ reflectionClass , 'isAnonymous' ) && $ reflectionClass -> isAnonymous ( ) ) { continue ; } if ( isset ( $ includedFiles [ $ sourceFile ] ) ) { $ classes [ $ className ] = true ; } } return [ array_keys ( $ classes ) , $ directoryList ] ; }
Gets the list of class names in the given directory .
50,171
private function registerClass ( ContainerBuilder $ container , $ className , array $ tags , array $ methods ) { if ( $ container -> has ( $ className ) ) { return ; } $ definition = $ container -> register ( $ className , $ className ) ; if ( method_exists ( $ definition , 'setAutowiredMethods' ) ) { $ definition -> setAutowiredMethods ( $ methods ) ; } else { $ definition -> setAutowired ( true ) ; } if ( is_a ( $ className , ContainerAwareInterface :: class , true ) ) { $ definition -> addMethodCall ( 'setContainer' , [ new Reference ( 'service_container' ) ] ) ; } foreach ( $ tags as $ tagClassName => $ classTags ) { if ( ! is_a ( $ className , $ tagClassName , true ) ) { continue ; } foreach ( $ classTags as $ classTag ) { $ definition -> addTag ( $ classTag [ 0 ] , $ classTag [ 1 ] ) ; } } }
Registers an action in the container .
50,172
public function file ( $ path ) { $ absolutePath = Asset :: isJavascript ( $ path ) ; if ( $ absolutePath ) { return $ this -> javascript ( $ absolutePath ) ; } $ absolutePath = Asset :: isStylesheet ( $ path ) ; if ( $ absolutePath ) { return $ this -> stylesheet ( $ absolutePath ) ; } $ absolutePath = Asset :: isFile ( $ path ) ; if ( $ absolutePath ) { $ this -> clientCacheForFile ( $ absolutePath ) ; return new BinaryFileResponse ( $ absolutePath , 200 ) ; } App :: abort ( 404 ) ; }
Returns a file in the assets directory
50,173
private function stylesheet ( $ path ) { $ response = Response :: make ( Asset :: stylesheet ( $ path ) , 200 ) ; $ response -> header ( 'Content-Type' , 'text/css' ) ; return $ response ; }
Returns css for the given path
50,174
private function clientCacheForFile ( $ path ) { $ lastModified = filemtime ( $ path ) ; if ( isset ( $ _SERVER [ 'HTTP_IF_MODIFIED_SINCE' ] ) && strtotime ( $ _SERVER [ 'HTTP_IF_MODIFIED_SINCE' ] ) >= $ lastModified ) { header ( 'HTTP/1.0 304 Not Modified' ) ; exit ; } }
Client cache regular files that are not javascript or stylesheets files
50,175
protected function attributesArrayToText ( $ attributes ) { $ text = "" ; foreach ( $ attributes as $ name => $ value ) { $ text .= "{$name}=\"{$value}\" " ; } $ text = rtrim ( $ text ) ; return $ text ; }
Convert the attributes array to a html text attributes
50,176
public function url_matcher ( $ matches ) { list ( $ changed , $ newurl ) = $ this -> relative_match ( $ matches [ 'url' ] ) ; if ( $ changed ) { return str_replace ( $ matches [ 'url' ] , $ newurl , $ matches [ 0 ] ) ; } list ( $ changed , $ newurl ) = $ this -> found_file_match ( $ matches [ 'url' ] ) ; if ( $ changed ) { return str_replace ( $ matches [ 'url' ] , $ newurl , $ matches [ 0 ] ) ; } return $ matches [ 0 ] ; }
My attempt at rewriting CSS urls . I am looking for all url tags and then I am going to try and resolve the correct absolute path from those urls . If the file actually exists then we are good else I just leave the thing alone .
50,177
protected function removeAssetCache ( $ file , $ recursive ) { $ files = $ this -> asset -> isJavascript ( $ file ) ? $ this -> asset -> getParser ( ) -> javascriptFiles ( $ file ) : $ this -> asset -> getParser ( ) -> stylesheetFiles ( $ file ) ; array_push ( $ files , $ this -> asset -> getParser ( ) -> absoluteFilePath ( $ file ) ) ; foreach ( $ files as $ file ) { $ removed = $ this -> asset -> getGenerator ( ) -> cachedFile ( $ file ) -> remove ( ) ; if ( $ removed === false ) { $ this -> writeln ( PHP_EOL . "<warning> failed to find/remove cache for {$file}</warning>" ) ; } } }
Removes the AssetCache for this file
50,178
public function imageTag ( $ filename , $ attributes ) { $ absolutePath = $ this -> file ( $ filename ) ; $ webPath = $ this -> parser -> absolutePathToWebPath ( $ absolutePath ) ; $ config = $ this -> getConfig ( ) ; $ composer = $ config [ 'image_tag' ] ; return $ composer -> process ( array ( $ webPath ) , array ( $ absolutePath ) , $ attributes ) ; }
Create image tag
50,179
public function isFile ( $ filename ) { $ absolutePath = $ this -> parser -> absoluteFilePath ( $ filename ) ; return file_exists ( $ absolutePath ) && is_file ( $ absolutePath ) ? $ absolutePath : null ; }
Is this filename any type of file?
50,180
public function setConfig ( array $ config ) { $ this -> parser -> config = $ config ; $ this -> generator -> config = $ config ; $ this -> registerAssetPipelineFilters ( ) ; }
Set the config array
50,181
public function registerAssetPipelineFilters ( ) { foreach ( $ this -> parser -> config [ 'filters' ] as $ filters ) { foreach ( $ filters as $ filter ) { if ( method_exists ( $ filter , 'setAssetPipeline' ) ) { $ filter -> setAssetPipeline ( $ this ) ; } } } foreach ( $ this -> generator -> config [ 'filters' ] as $ filters ) { foreach ( $ filters as $ filter ) { if ( method_exists ( $ filter , 'setAssetPipeline' ) ) { $ filter -> setAssetPipeline ( $ this ) ; } } } return $ this ; }
This calls a method on every filter we have to pass in the current pipeline if that method exists
50,182
public function process ( $ paths , $ absolutePaths , $ attributes ) { $ url = url ( ) ; $ attributesAsText = $ this -> attributesArrayToText ( $ attributes ) ; foreach ( $ paths as $ path ) { print "<link href=\"{$url}{$path}\" {$attributesAsText} rel=\"stylesheet\" type=\"text/css\">" . PHP_EOL ; } }
Process the paths that come through the asset pipeline
50,183
public function compileMap ( ResolverInterface $ resolver ) : array { if ( $ resolver instanceof AggregateResolver ) { return $ this -> compileFromAggregateResolver ( $ resolver ) ; } if ( $ resolver instanceof TemplatePathStack ) { return $ this -> compileFromTemplatePathStack ( $ resolver ) ; } if ( $ resolver instanceof TemplateMapResolver ) { return $ this -> compileFromTemplateMapResolver ( $ resolver ) ; } return [ ] ; }
Generates a list of all existing templates in the given resolver with their names being keys and absolute paths being values
50,184
private function addResolvedPath ( SplFileInfo $ file , array & $ map , $ basePath , TemplatePathStack $ resolver ) { $ filePath = $ file -> getRealPath ( ) ; $ fileName = pathinfo ( $ filePath , PATHINFO_FILENAME ) ; $ relativePath = trim ( str_replace ( $ basePath , '' , $ file -> getPath ( ) ) , '/\\' ) ; $ templateName = str_replace ( '\\' , '/' , trim ( $ relativePath . '/' . $ fileName , '/' ) ) ; if ( $ fileName && ( $ resolvedPath = $ resolver -> resolve ( $ templateName ) ) ) { $ map [ $ templateName ] = realpath ( $ resolvedPath ) ; } }
Add the given file to the map if it corresponds to a resolved view
50,185
private function loadMap ( ) { $ this -> map = $ this -> cache -> getItem ( $ this -> cacheKey ) ; if ( is_array ( $ this -> map ) ) { return ; } $ realResolverInstantiator = $ this -> realResolverInstantiator ; $ realResolver = $ realResolverInstantiator ( ) ; if ( ! $ realResolver instanceof ResolverInterface ) { throw InvalidResolverInstantiatorException :: fromInvalidResolver ( $ realResolver ) ; } $ this -> map = ( new TemplateMapCompiler ( ) ) -> compileMap ( $ realResolver ) ; $ this -> cache -> setItem ( $ this -> cacheKey , $ this -> map ) ; }
Load the template map into memory
50,186
public function encode ( string $ data ) : string { if ( true === $ this -> options [ "check" ] ) { $ data = chr ( $ this -> options [ "version" ] ) . $ data ; $ hash = hash ( "sha256" , $ data , true ) ; $ hash = hash ( "sha256" , $ hash , true ) ; $ checksum = substr ( $ hash , 0 , 4 ) ; $ data .= $ checksum ; } $ data = str_split ( $ data ) ; $ data = array_map ( "ord" , $ data ) ; $ leadingZeroes = 0 ; while ( ! empty ( $ data ) && 0 === $ data [ 0 ] ) { $ leadingZeroes ++ ; array_shift ( $ data ) ; } $ converted = $ this -> baseConvert ( $ data , 256 , 58 ) ; if ( 0 < $ leadingZeroes ) { $ converted = array_merge ( array_fill ( 0 , $ leadingZeroes , 0 ) , $ converted ) ; } return implode ( "" , array_map ( function ( $ index ) { return $ this -> options [ "characters" ] [ $ index ] ; } , $ converted ) ) ; }
Encode given data to a base58 string
50,187
public function decode ( string $ data ) : string { $ this -> validateInput ( $ data ) ; $ data = str_split ( $ data ) ; $ data = array_map ( function ( $ character ) { return strpos ( $ this -> options [ "characters" ] , $ character ) ; } , $ data ) ; $ leadingZeroes = 0 ; while ( ! empty ( $ data ) && 0 === $ data [ 0 ] ) { $ leadingZeroes ++ ; array_shift ( $ data ) ; } $ converted = $ this -> baseConvert ( $ data , 58 , 256 ) ; if ( 0 < $ leadingZeroes ) { $ converted = array_merge ( array_fill ( 0 , $ leadingZeroes , 0 ) , $ converted ) ; } $ decoded = implode ( "" , array_map ( "chr" , $ converted ) ) ; if ( true === $ this -> options [ "check" ] ) { $ hash = substr ( $ decoded , 0 , - ( Base58 :: CHECKSUM_SIZE ) ) ; $ hash = hash ( "sha256" , $ hash , true ) ; $ hash = hash ( "sha256" , $ hash , true ) ; $ checksum = substr ( $ hash , 0 , Base58 :: CHECKSUM_SIZE ) ; if ( 0 !== substr_compare ( $ decoded , $ checksum , - ( Base58 :: CHECKSUM_SIZE ) ) ) { $ message = sprintf ( 'Checksum "%s" does not match the expected "%s"' , bin2hex ( substr ( $ decoded , - ( Base58 :: CHECKSUM_SIZE ) ) ) , bin2hex ( $ checksum ) ) ; throw new RuntimeException ( $ message ) ; } $ version = substr ( $ decoded , 0 , Base58 :: VERSION_SIZE ) ; $ version = ord ( $ version ) ; if ( $ version !== $ this -> options [ "version" ] ) { $ message = sprintf ( 'Version "%s" does not match the expected "%s"' , $ version , $ this -> options [ "version" ] ) ; throw new RuntimeException ( $ message ) ; } $ decoded = substr ( $ decoded , Base58 :: VERSION_SIZE , - ( Base58 :: CHECKSUM_SIZE ) ) ; } return $ decoded ; }
Decode given base58 string back to data
50,188
public function set ( $ key , $ value ) { $ config = & $ this -> config ; foreach ( explode ( '.' , $ key ) as $ k ) { $ config = & $ config [ $ k ] ; } $ config = $ value ; return true ; }
Store a config value with a specified key .
50,189
public function get ( $ key , $ default = null ) { $ config = $ this -> config ; foreach ( explode ( '.' , $ key ) as $ k ) { if ( ! isset ( $ config [ $ k ] ) ) { return $ default ; } $ config = $ config [ $ k ] ; } return $ config ; }
Retrieve a configuration option via a provided key .
50,190
public function has ( $ key ) { $ config = $ this -> config ; foreach ( explode ( '.' , $ key ) as $ k ) { if ( ! isset ( $ config [ $ k ] ) ) { return false ; } $ config = $ config [ $ k ] ; } return true ; }
Check for the existence of a configuration item .
50,191
public function load ( $ path , $ prefix = null , $ override = true ) { $ file = new SplFileInfo ( $ path ) ; $ className = $ file -> isDir ( ) ? 'Directory' : ucfirst ( strtolower ( $ file -> getExtension ( ) ) ) ; $ classPath = 'PHLAK\\Config\\Loaders\\' . $ className ; $ loader = new $ classPath ( $ file -> getRealPath ( ) ) ; $ newConfig = $ prefix ? [ $ prefix => $ loader -> getArray ( ) ] : $ loader -> getArray ( ) ; if ( $ override ) { $ this -> config = array_replace_recursive ( $ this -> config , $ newConfig ) ; } else { $ this -> config = array_replace_recursive ( $ newConfig , $ this -> config ) ; } return $ this ; }
Load configuration options from a file or directory .
50,192
public function merge ( self $ config , $ override = true ) { if ( $ override ) { $ this -> config = array_replace_recursive ( $ this -> config , $ config -> toArray ( ) ) ; } else { $ this -> config = array_replace_recursive ( $ config -> toArray ( ) , $ this -> config ) ; } return $ this ; }
Merge another Config object into this one .
50,193
public function getArray ( ) { $ contents = [ ] ; foreach ( new DirectoryIterator ( $ this -> context ) as $ file ) { if ( $ file -> isDot ( ) ) { continue ; } $ className = $ file -> isDir ( ) ? 'Directory' : ucfirst ( strtolower ( $ file -> getExtension ( ) ) ) ; $ classPath = 'PHLAK\\Config\\Loaders\\' . $ className ; $ loader = new $ classPath ( $ file -> getPathname ( ) ) ; try { $ contents = array_merge ( $ contents , $ loader -> getArray ( ) ) ; } catch ( InvalidFileException $ e ) { } } return $ contents ; }
Retrieve the contents of one or more configuration files in a directory and convert them to an array of configuration options . Any invalid files will be silently ignored .
50,194
public static function getKeyUri ( $ type , $ label , $ secret , $ counter = null , $ options = array ( ) ) { if ( ! in_array ( $ type , self :: $ allowedTypes ) ) { throw new \ InvalidArgumentException ( 'Type has to be of allowed types list' ) ; } $ label = trim ( $ label ) ; if ( strlen ( $ label ) < 1 ) { throw new \ InvalidArgumentException ( 'Label has to be one or more printable characters' ) ; } if ( substr_count ( $ label , ':' ) > 2 ) { throw new \ InvalidArgumentException ( 'Account name contains illegal colon characters' ) ; } if ( strlen ( $ secret ) < 1 ) { throw new \ InvalidArgumentException ( 'No secret present' ) ; } if ( $ type == 'hotp' && is_null ( $ counter ) ) { throw new \ InvalidArgumentException ( 'Counter required for hotp' ) ; } $ otpauth = 'otpauth://' . $ type . '/' . rawurlencode ( $ label ) . '?secret=' . rawurlencode ( $ secret ) ; if ( $ type == 'hotp' && ! is_null ( $ counter ) ) { $ otpauth .= '&counter=' . intval ( $ counter ) ; } if ( array_key_exists ( 'algorithm' , $ options ) ) { $ otpauth .= '&algorithm=' . rawurlencode ( $ options [ 'algorithm' ] ) ; } if ( array_key_exists ( 'digits' , $ options ) && intval ( $ options [ 'digits' ] ) !== 6 && intval ( $ options [ 'digits' ] ) !== 8 ) { throw new \ InvalidArgumentException ( 'Digits can only have the values 6 or 8, ' . $ options [ 'digits' ] . ' given' ) ; } elseif ( array_key_exists ( 'digits' , $ options ) ) { $ otpauth .= '&digits=' . intval ( $ options [ 'digits' ] ) ; } if ( $ type == 'totp' && array_key_exists ( 'period' , $ options ) ) { $ otpauth .= '&period=' . rawurlencode ( $ options [ 'period' ] ) ; } if ( array_key_exists ( 'issuer' , $ options ) ) { $ otpauth .= '&issuer=' . rawurlencode ( $ options [ 'issuer' ] ) ; } if ( array_key_exists ( 'image' , $ options ) ) { $ otpauth .= '&image=' . $ options [ 'image' ] ; } return $ otpauth ; }
Returns the Key URI
50,195
public static function getQrCodeUrl ( $ type , $ label , $ secret , $ counter = null , $ options = array ( ) ) { $ width = self :: $ width ; if ( array_key_exists ( 'width' , $ options ) && is_numeric ( $ options [ 'width' ] ) ) { $ width = $ options [ 'width' ] ; } $ height = self :: $ height ; if ( array_key_exists ( 'height' , $ options ) && is_numeric ( $ options [ 'height' ] ) ) { $ height = $ options [ 'height' ] ; } $ otpauth = self :: getKeyUri ( $ type , $ label , $ secret , $ counter , $ options ) ; $ url = 'https://chart.googleapis.com/chart?chs=' . $ width . 'x' . $ height . '&cht=qr&chld=M|0&chl=' . urlencode ( $ otpauth ) ; return $ url ; }
Returns the QR code url
50,196
public static function generateRandom ( $ length = 16 ) { $ keys = array_merge ( range ( 'A' , 'Z' ) , range ( 2 , 7 ) ) ; $ string = '' ; for ( $ i = 0 ; $ i < $ length ; $ i ++ ) { $ string .= $ keys [ random_int ( 0 , 31 ) ] ; } return $ string ; }
Creates a pseudo random Base32 string
50,197
public static function generateRecoveryCodes ( $ count = 1 , $ length = 9 ) { $ count = intval ( $ count ) ; $ length = intval ( $ length ) ; $ codes = [ ] ; do { $ code = '' ; for ( $ i = 1 ; $ i <= $ length ; $ i ++ ) { $ code .= random_int ( 0 , 9 ) ; } if ( ! in_array ( $ code , $ codes ) ) { $ codes [ ] = $ code ; } } while ( count ( $ codes ) < $ count ) ; return $ codes ; }
Create recovery codes
50,198
public function getArray ( ) { try { $ parsed = YamlParser :: parse ( file_get_contents ( $ this -> context ) ) ; } catch ( ParseException $ e ) { throw new InvalidFileException ( $ e -> getMessage ( ) ) ; } if ( ! is_array ( $ parsed ) ) { throw new InvalidFileException ( 'Unable to parse invalid YAML file at ' . $ this -> context ) ; } return $ parsed ; }
Retrieve the contents of a . yaml file and convert it to an array of configuration options .
50,199
public function setAlgorithm ( $ algorithm ) { if ( ! in_array ( $ algorithm , $ this -> allowedAlgorithms ) ) { throw new \ InvalidArgumentException ( 'Not an allowed algorithm: ' . $ algorithm ) ; } $ this -> algorithm = $ algorithm ; return $ this ; }
Changing the used algorithm for hashing