idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
35,600
protected function getShortOsName ( Request $ request ) { $ os = strtolower ( $ request -> headers -> get ( 'User-Agent' ) ) ; if ( false !== strpos ( $ os , 'linux' ) ) { return 'linux' ; } if ( ( false !== strpos ( $ os , 'macintosh' ) ) || ( false !== strpos ( $ os , 'mac os x' ) ) ) { return 'mac' ; } return 'windows' ; }
Detect OS based on User - Agent header
35,601
protected function getCountry ( Request $ request ) { if ( $ request -> headers -> get ( 'CF-IPCountry' ) ) { return strtolower ( $ request -> headers -> get ( 'CF-IPCountry' ) ) ; } if ( is_callable ( 'geoip_country_code_by_name' ) ) { if ( $ countryCode = @ geoip_country_code_by_name ( $ request -> getClientIp ( ) ) ) { return strtolower ( $ countryCode ) ; } } return 'unknown' ; }
Detect country based on IP
35,602
private function getGroupId ( ) : ? string { $ group = $ this -> getPanelGroup ( ) ; if ( ! $ group ) { return null ; } $ cssID = StringUtil :: deserialize ( $ group -> cssID , true ) ; if ( is_string ( $ cssID [ 0 ] ) && $ cssID [ 0 ] !== '' ) { return $ cssID [ 0 ] ; } return 'panel-group-' . $ group -> id ; }
Get the panel group id .
35,603
public function setValue ( $ value ) { if ( ! is_string ( $ value ) && ! is_int ( $ value ) ) { throw new \ InvalidArgumentException ( 'A RadioGroup value must be a string or int' ) ; } $ this -> value = $ value ; foreach ( $ this -> getContents ( ) as $ item ) { if ( $ item -> getValue ( ) == $ value ) { $ item -> setChecked ( true ) ; } else { $ item -> setChecked ( false ) ; } } return $ this ; }
Sets which radio button is checked
35,604
public function set ( $ key , $ value ) { if ( ! $ value instanceof Radio ) { throw new \ InvalidArgumentException ( 'Only Radios can be added to a RadioGroup' ) ; } return parent :: set ( $ key , $ value ) ; }
Extends the set method to ensure that only Radios can be added to a RadioGroup
35,605
public function render ( Render $ renderer ) { $ radios = [ ] ; foreach ( $ this -> getContents ( ) as $ radio ) { $ radios [ ] = $ renderer -> render ( $ radio ) ; } return implode ( '' , $ radios ) ; }
Renders a group of radio buttons
35,606
public function bind ( $ value ) { Argument :: i ( ) -> test ( 1 , 'array' , 'string' , 'numeric' , 'null' ) ; if ( is_array ( $ value ) ) { foreach ( $ value as $ i => $ item ) { $ value [ $ i ] = $ this -> bind ( $ item ) ; } return '(' . implode ( "," , $ value ) . ')' ; } else if ( is_int ( $ value ) || ctype_digit ( $ value ) ) { return $ value ; } $ name = ':bind' . count ( $ this -> binds ) . 'bind' ; $ this -> binds [ $ name ] = $ value ; return $ name ; }
Binds a value and returns the bound key
35,607
public function getQueries ( $ index = null ) { Argument :: i ( ) -> test ( 1 , 'int' , 'string' , 'null' ) ; if ( is_null ( $ index ) ) { return $ this -> queries ; } if ( $ index == self :: FIRST ) { $ index = 0 ; } else if ( $ index == self :: LAST ) { $ index = count ( $ this -> queries ) - 1 ; } if ( isset ( $ this -> queries [ $ index ] ) ) { return $ this -> queries [ $ index ] ; } return null ; }
Returns the history of queries made still in memory
35,608
public function setCollection ( $ collection ) { Argument :: i ( ) -> test ( 1 , 'string' ) ; if ( $ collection != self :: COLLECTION && ! is_subclass_of ( $ collection , self :: COLLECTION ) ) { Exception :: i ( ) -> setMessage ( Exception :: NOT_SUB_COLLECTION ) -> addVariable ( $ collection ) -> trigger ( ) ; } $ this -> collection = $ collection ; return $ this ; }
Sets default collection
35,609
public function actionReport ( ) { $ hasErrors = false ; foreach ( $ this -> getAuditManager ( ) -> getReport ( ) as $ modelName => $ result ) { if ( is_string ( $ result ) || ! $ result [ 'enabled' ] ) { $ color = Console :: FG_GREY ; } elseif ( $ result [ 'valid' ] === false ) { $ hasErrors = false ; $ color = Console :: FG_RED ; } else { $ color = Console :: FG_GREEN ; } $ this -> stdout ( ' ' . str_pad ( is_string ( $ result ) ? $ result : $ modelName . ' ' , 40 , '.' ) . ' ' , $ color ) ; if ( is_array ( $ result ) ) { $ this -> stdout ( $ result [ 'enabled' ] ? '+' : '-' , $ color ) ; $ this -> stdout ( $ result [ 'valid' ] === false ? '!' : '' , $ color ) ; } $ this -> stdout ( "\n" ) ; } return $ hasErrors ? self :: EXIT_CODE_ERROR : self :: EXIT_CODE_NORMAL ; }
Displays a list of all models from every module and its audits status .
35,610
public function actionMigration ( $ modelName = null ) { $ queryTemplate = <<<EOD \$query = <<<SQL{Query}SQL; \$this->execute(\$query);EOD ; $ queries = [ 'up' => [ ] , 'down' => [ ] , ] ; foreach ( $ this -> getAuditManager ( ) -> getDbCommands ( $ modelName , 'up' ) as $ command ) { $ queries [ 'up' ] [ ] = strtr ( $ queryTemplate , [ '{Query}' => $ command -> getSql ( ) ] ) ; } foreach ( $ this -> getAuditManager ( ) -> getDbCommands ( $ modelName , 'down' ) as $ command ) { $ queries [ 'down' ] [ ] = strtr ( $ queryTemplate , [ '{Query}' => $ command -> getSql ( ) ] ) ; } if ( empty ( $ queries [ 'up' ] ) && empty ( $ queries [ 'down' ] ) ) { $ this -> stdout ( 'Warning: nothing to do, would create an empty migration.' . "\n" , Console :: FG_YELLOW ) ; return self :: EXIT_CODE_ERROR ; } $ name = 'm' . gmdate ( 'ymd_His' ) . '_audit' ; if ( $ modelName !== null ) { $ parts = explode ( '\\' , $ modelName ) ; $ modelName = end ( $ parts ) ; $ name .= '_' . $ modelName ; } $ file = $ this -> migrationPath . DIRECTORY_SEPARATOR . $ name . '.php' ; if ( $ this -> confirm ( "Create new migration '$file'?" ) ) { $ content = $ this -> getTemplate ( $ name , $ queries ) ; file_put_contents ( $ file , $ content ) ; $ this -> stdout ( "New migration created successfully.\n" , Console :: FG_GREEN ) ; } return self :: EXIT_CODE_NORMAL ; }
Creates a migration file that install audit database objects .
35,611
public function create ( $ columns , $ options = 'charset=utf8 engine=innodb' ) { $ columnSql = array ( ) ; $ platform = $ this -> _connection -> platform ( ) ; foreach ( $ columns as $ name => $ type ) $ columnSql [ ] = $ type -> columnSql ( $ name , $ platform ) ; $ sql = sprintf ( 'CREATE TABLE %s (%s) %s' , $ this -> _name -> quoted ( ) , implode ( ', ' , $ columnSql ) , $ options ) ; $ this -> _connection -> execute ( $ sql ) ; }
Creates the table fails if the table exists
35,612
public function columns ( ) { if ( ! isset ( $ this -> _columns ) ) { $ this -> _columns = array ( ) ; foreach ( $ this -> _connection -> execute ( "SHOW COLUMNS FROM " . $ this -> _name -> quoted ( ) ) as $ c ) { $ column = $ c [ 'Field' ] ; unset ( $ c [ 'Field' ] ) ; $ this -> _columns [ $ column ] = $ c ; } } return $ this -> _columns ; }
Returns all the database columns in SHOW COLUMN format
35,613
public function update ( $ data , Criteria $ where , $ limit = false ) { if ( empty ( $ data ) ) throw new Exception ( "Can't insert an empty row" ) ; return $ this -> _connection -> execute ( sprintf ( 'UPDATE %s SET %s WHERE %s%s' , $ this -> _name -> quoted ( ) , $ this -> _buildSet ( $ data ) , $ where , $ limit ? ' LIMIT ' . intval ( $ limit ) : '' ) , array_values ( $ data ) ) ; }
Updates a row into the table
35,614
public function upsert ( $ data ) { if ( empty ( $ data ) ) throw new Exception ( "Can't insert an empty row" ) ; return $ this -> _connection -> execute ( sprintf ( 'INSERT INTO %s SET %2$s ON DUPLICATE KEY UPDATE %2$s' , $ this -> _name -> quoted ( ) , $ this -> _buildSet ( $ data ) ) , array_merge ( array_values ( $ data ) , array_values ( $ data ) ) ) ; }
Tries to update a record or inserts if it doesn t exist . Worth noting that affectedRows will be 2 on an update 1 on an insert .
35,615
public function delete ( $ criteria = NULL ) { $ where = ! is_null ( $ criteria ) ? 'WHERE ' . $ criteria -> toSql ( ) : NULL ; return $ this -> _connection -> execute ( sprintf ( 'DELETE FROM %s %s' , $ this -> _name -> quoted ( ) , $ where ) ) ; }
Deletes rows in the table
35,616
public function query ( $ criteria = null ) { $ query = new \ Pheasant \ Query \ Query ( $ this -> _connection ) ; $ query -> from ( $ this -> _name ) ; if ( ! is_null ( $ criteria ) ) $ query -> where ( $ criteria ) ; return $ query ; }
Builds a Query object for the table
35,617
private function _buildSet ( $ data ) { $ columns = [ ] ; foreach ( $ data as $ key => $ value ) $ columns [ ] = sprintf ( '`%s`=?' , $ key ) ; return implode ( ', ' , $ columns ) ; }
Builds a series of X = ? Y = ? Z = ?
35,618
public function cookies ( $ name = null , $ val = null , array $ params = array ( ) ) { $ num = func_num_args ( ) ; if ( ! $ num ) return $ this -> _dispatcher ( ) -> response ( ) -> cookies ( ) ; elseif ( $ num == 1 ) return $ this -> _dispatcher ( ) -> response ( ) -> cookies ( ) -> get ( $ name ) ; else { if ( $ val === null ) $ this -> _dispatcher ( ) -> response ( ) -> cookies ( ) -> delete ( $ name ) ; else return $ this -> _dispatcher ( ) -> response ( ) -> cookies ( ) -> add ( $ name , $ val , $ params ) ; } }
Retrieves Cookies instance retrieves a cookie or sets a cookie .
35,619
public function generate ( Basket $ basket ) { $ total = 0 ; foreach ( $ basket -> products ( ) as $ product ) { if ( $ product -> taxable ) { $ total = $ total + $ product -> quantity ; } } return $ total ; }
Generate the Meta Data
35,620
public static function create ( RouteCollection $ routes ) : self { $ factory = new PathPatternFactory ( ) ; $ compiler = new MultiPatternCompiler ( $ factory ) ; return new self ( $ routes , $ compiler ) ; }
Creates new router for given routes .
35,621
public static function register ( $ registerViewExtension = false , Recaptcha $ recaptcha = null , $ appName = null ) { $ app = call_user_func_array ( [ '\Slim\Slim' , 'getInstance' ] , array_filter ( [ $ appName ] ) ) ; $ recaptcha = self :: registerSingleton ( $ app , $ recaptcha ) ; if ( $ registerViewExtension ) { self :: registerViewExtension ( $ app , $ recaptcha ) ; } }
Register a Recaptcha instance with the application container .
35,622
private static function registerSingleton ( Slim $ app , Recaptcha $ recaptcha = null ) { if ( is_null ( $ recaptcha ) ) { $ config = $ app -> config ( 'recaptcha' ) ; $ recaptcha = new Recaptcha ( $ config [ 'secret' ] , $ config [ 'siteKey' ] ) ; } $ app -> container -> singleton ( 'recaptcha' , function ( ) use ( $ recaptcha ) { return $ recaptcha ; } ) ; return $ recaptcha ; }
Register the singleton with the application container .
35,623
private static function registerViewExtension ( Slim $ app , Recaptcha $ recaptcha ) { $ view = $ app -> view ; if ( ! property_exists ( $ view , 'parserExtensions' ) ) { return ; } $ originalExtensions = $ view -> parserExtensions ? : [ ] ; $ class = explode ( '\\' , get_class ( $ view ) ) ; switch ( end ( $ class ) ) { case 'Twig' : $ view -> parserExtensions = array_merge ( $ originalExtensions , [ new TwigExtension ( $ recaptcha ) ] ) ; break ; } }
Register the available parser extension .
35,624
public function filteredSelectOptions ( ) { $ tasks = $ this -> Roles -> Tasks -> find ( 'list' , [ 'limit' => 200 ] ) ; $ users = $ this -> Roles -> Users -> find ( 'list' , [ 'limit' => 200 ] ) ; $ this -> set ( compact ( 'tasks' , 'users' ) ) ; }
This function is used to filter select options
35,625
public function remove ( $ content_path ) { $ UPLOAD_DIR = ( Configure :: check ( 'DEFAULT_UPLOAD_DIR' ) ? Configure :: read ( 'DEFAULT_UPLOAD_DIR' ) : WWW_ROOT . 'uploads' ) ; $ file = new File ( $ UPLOAD_DIR . $ content_path ) ; return $ file -> delete ( ) ; }
Delete file from filesystem
35,626
public function getPermittedFileName ( $ directory , $ filename ) { $ pathInfo = pathinfo ( $ filename ) ; $ pathInfo [ 'filename' ] = substr ( Inflector :: slug ( $ pathInfo [ 'filename' ] ) , 0 , 100 ) ; if ( strlen ( $ pathInfo [ 'filename' ] ) < 3 ) $ pathInfo [ 'filename' ] = $ this -> _randomString ( ) ; $ dir = new Folder ( $ directory ) ; $ iter = 0 ; do { if ( $ iter == 0 ) $ slugFileName = $ pathInfo [ 'filename' ] . '.' . $ pathInfo [ 'extension' ] ; else $ slugFileName = $ pathInfo [ 'filename' ] . '-' . $ iter . '.' . $ pathInfo [ 'extension' ] ; $ data = $ dir -> find ( $ slugFileName , true ) ; $ iter ++ ; } while ( count ( $ data ) > 0 ) ; return $ slugFileName ; }
Returns the valid file name to use for upload
35,627
public static function all ( ) : array { return [ self :: OPTIONS , self :: GET , self :: HEAD , self :: POST , self :: PUT , self :: PATCH , self :: DELETE , ] ; }
Returns all recognized methods .
35,628
public static function isAlwaysAllowed ( string $ method ) : bool { return in_array ( $ method , [ self :: HEAD , self :: GET ] ) ; }
Determine if the given method is always allowed .
35,629
public function addTemplates ( $ templates ) { foreach ( $ templates as $ name => $ template ) { $ this -> twig -> getLoader ( ) -> setTemplate ( $ name , $ template ) ; } }
Add templates as a map of name to template to the template loader .
35,630
public function getTrandsPlace ( array $ parameters = array ( ) , $ multipart = false , $ appOnlyAuth = false ) { return $ this -> get ( 'trends/place' , $ parameters , $ multipart , $ appOnlyAuth ) ; }
Returns the top 10 trending topics for a specific WOEID if trending information is available for it .
35,631
public function getTrandsAvailable ( array $ parameters = array ( ) , $ multipart = false , $ appOnlyAuth = false ) { return $ this -> get ( 'trends/available' , $ parameters , $ multipart , $ appOnlyAuth ) ; }
Returns the locations that Twitter has trending topic information for .
35,632
public function getTrendsClosest ( array $ parameters = array ( ) , $ multipart = false , $ appOnlyAuth = false ) { return $ this -> get ( 'trends/closest' , $ parameters , $ multipart , $ appOnlyAuth ) ; }
Returns the locations that Twitter has trending topic information for closest to a specified location .
35,633
public function processMultipleRegions ( ) { return new Pool ( $ this -> client , $ this -> requests , [ 'concurrency' => 18 , 'fulfilled' => function ( $ response , $ index ) { array_push ( $ this -> acceptedResponsesJson , json_decode ( $ response -> getBody ( ) -> getContents ( ) ) ) ; } , 'rejected' => function ( $ reason , $ index ) { array_push ( $ this -> rejectedResponse , $ reason ) ; } , ] ) ; }
Processes multiple regions pushing accpted requests to an array .
35,634
public function createRegionRequestsForPool ( Array $ regionHrefs ) { $ this -> resetContainers ( ) ; foreach ( $ regionHrefs as $ regionHref ) { array_push ( $ this -> requests , new Request ( 'GET' , $ regionHref ) ) ; } }
Create a set of region requests for a pool .
35,635
public function attributeWas ( $ attr ) { return $ this -> attributeChanged ( $ attr ) ? $ this -> changedAttributes [ $ attr ] : $ this -> getAttribute ( $ attr ) ; }
This method returns the previous value of an attribute before updating a record . If it was not changed returns null .
35,636
public function delete ( $ id ) { $ item = $ this -> itemRepository -> findById ( $ id ) ; if ( ! $ item ) { throw new ItemNotFoundException ( $ id ) ; } $ this -> em -> remove ( $ item ) ; $ this -> em -> flush ( ) ; }
Deletes an item .
35,637
public function findEntityById ( $ id ) { $ item = $ this -> itemRepository -> find ( $ id ) ; if ( ! $ item ) { return null ; } return $ item ; }
Finds an item entity by id .
35,638
public function retrieveTaxForClass ( TaxClass $ taxClass ) { $ locale = $ this -> shopLocation ; $ countryTax = $ this -> countryTaxRepository -> findByLocaleAndTaxClassId ( $ locale , $ taxClass -> getId ( ) ) ; if ( ! $ countryTax ) { $ countryTax = $ this -> countryTaxRepository -> findByLocaleAndTaxClassId ( $ locale , TaxClass :: STANDARD_TAX_RATE ) ; if ( ! $ countryTax ) { return 0 ; } } return $ countryTax -> getTax ( ) ; }
Retrieves the tax depending on the current class and configured shop location .
35,639
protected function setItemDeliveryAddress ( $ addressData , ApiItemInterface $ item , ContactInterface $ contact = null , AccountInterface $ account = null ) { if ( $ item -> getDeliveryAddress ( ) === null ) { $ deliveryAddress = new $ this -> orderAddressEntity ( ) ; $ this -> em -> persist ( $ deliveryAddress ) ; $ item -> setDeliveryAddress ( $ deliveryAddress ) ; } if ( is_array ( $ addressData ) ) { $ this -> orderAddressManager -> setOrderAddress ( $ item -> getDeliveryAddress ( ) , $ addressData , $ contact , $ account ) ; } elseif ( is_int ( $ addressData ) ) { $ contactAddressId = $ addressData ; $ deliveryAddress = $ item -> getEntity ( ) -> getDeliveryAddress ( ) ; $ orderAddress = $ this -> orderAddressManager -> getAndSetOrderAddressByContactAddressId ( $ contactAddressId , $ contact , $ account , $ deliveryAddress ) ; $ item -> setDeliveryAddress ( $ orderAddress ) ; if ( ! $ deliveryAddress ) { $ this -> em -> persist ( $ orderAddress ) ; } } }
Sets delivery address for an item .
35,640
private function checkRequiredData ( $ data , $ isNew ) { if ( array_key_exists ( 'product' , $ data ) ) { $ this -> getProductId ( $ data [ 'product' ] , 'product.id' ) ; } else { $ this -> checkDataSet ( $ data , 'name' , $ isNew ) ; $ this -> checkDataSet ( $ data , 'quantityUnit' , $ isNew ) ; } $ this -> checkDataSet ( $ data , 'quantity' , $ isNew ) ; }
Check if necessary data is set .
35,641
protected function setItemByProductData ( $ productData , ApiItemInterface $ item , $ locale ) { $ productId = $ this -> getProductId ( $ productData , 'product.id' ) ; $ product = $ this -> productRepository -> find ( $ productId ) ; if ( ! $ product ) { throw new ProductNotFoundException ( self :: $ productEntityName , $ productId ) ; } $ item -> setProduct ( $ product ) ; $ translation = $ product -> getTranslation ( $ locale ) ; if ( is_null ( $ translation ) ) { if ( count ( $ product -> getTranslations ( ) ) > 0 ) { $ translation = $ product -> getTranslations ( ) [ 0 ] ; } else { throw new ProductException ( 'Product ' . $ product -> getId ( ) . ' has no translations!' ) ; } } $ this -> setItemSupplier ( $ item , $ product ) ; $ item -> setName ( $ translation -> getName ( ) ) ; $ item -> setDescription ( $ translation -> getLongDescription ( ) ) ; $ item -> setNumber ( $ product -> getNumber ( ) ) ; if ( $ product -> getOrderUnit ( ) ) { $ item -> setQuantityUnit ( $ product -> getOrderUnit ( ) -> getTranslation ( $ locale ) -> getName ( ) ) ; } else if ( $ product -> getParent ( ) && $ product -> getParent ( ) -> getOrderUnit ( ) ) { $ item -> setQuantityUnit ( $ product -> getParent ( ) -> getOrderUnit ( ) -> getTranslation ( $ locale ) -> getName ( ) ) ; } $ item -> setIsRecurringPrice ( $ product -> isRecurringPrice ( ) ) ; $ taxClass = $ product -> getTaxClass ( ) ; if ( ! $ taxClass && $ product -> getParent ( ) ) { $ taxClass = $ product -> getParent ( ) -> getTaxClass ( ) ; } if ( $ taxClass ) { $ tax = $ this -> retrieveTaxForClass ( $ taxClass ) ; $ item -> setTax ( $ tax ) ; } else { $ item -> setTax ( 0 ) ; } return $ product ; }
Sets item based on given product data .
35,642
protected function setAddonData ( ItemInterface $ lastProcessedProductItem , ItemInterface $ item , ProductInterface $ parentItemProduct = null ) { $ item -> setParent ( $ lastProcessedProductItem ) ; $ parentProduct = $ lastProcessedProductItem -> getProduct ( ) ; $ addonProduct = $ item -> getProduct ( ) ; $ addon = $ this -> addonRepository -> findOneBy ( [ 'product' => $ parentProduct , 'addon' => $ addonProduct ] ) ; if ( ! $ addon && $ parentItemProduct ) { $ addon = $ this -> addonRepository -> findOneBy ( [ 'product' => $ parentProduct , 'addon' => $ parentItemProduct ] ) ; } if ( ! $ addon ) { throw new \ Exception ( 'Addon id ' . $ addonProduct -> getId ( ) . ' for product id ' . $ parentProduct -> getId ( ) . ' not found.' ) ; } $ item -> setAddon ( $ addon ) ; return $ addon ; }
Set addon data to item .
35,643
protected function setItemSupplier ( ApiItemInterface $ item , ProductInterface $ product ) { $ supplier = null ; $ supplierName = '' ; if ( $ product -> getSupplier ( ) ) { $ supplier = $ product -> getSupplier ( ) ; $ supplierName = $ product -> getSupplier ( ) -> getName ( ) ; } $ item -> setSupplier ( $ supplier ) ; $ item -> setSupplierName ( $ supplierName ) ; }
Set supplier of an item .
35,644
public function getDirectMessages ( array $ parameters = array ( ) , $ multipart = false , $ appOnlyAuth = false ) { return $ this -> get ( 'direct_messages' , $ parameters , $ multipart , $ appOnlyAuth ) ; }
Returns the 20 most recent direct messages sent to the authenticating user . Includes detailed information about the sender and recipient user . You can request up to 200 direct messages per call up to a maximum of 800 incoming DMs
35,645
public function getDirectMessagesSent ( array $ parameters = array ( ) , $ multipart = false , $ appOnlyAuth = false ) { return $ this -> get ( 'direct_messages/sent' , $ parameters , $ multipart , $ appOnlyAuth ) ; }
Returns the 20 most recent direct messages sent by the authenticating user . Includes detailed information about the sender and recipient user . You can request up to 200 direct messages per call up toa maximum of 800 outgoing DMs .
35,646
public function postDirectMessagesDestroy ( array $ parameters = array ( ) , $ multipart = false , $ appOnlyAuth = false ) { return $ this -> post ( 'direct_messages/destroy' , $ parameters , $ multipart , $ appOnlyAuth ) ; }
Destroys the direct message specified in the required ID parameter . The authenticating user must be the recipient of the specified direct message .
35,647
public function postDirectMessagesNew ( array $ parameters = array ( ) , $ multipart = false , $ appOnlyAuth = false ) { return $ this -> post ( 'direct_messages/new' , $ parameters , $ multipart , $ appOnlyAuth ) ; }
Sends a new direct message to the specified user from the authenticating user .
35,648
public function getTableIndexByColumnsName ( $ columnNames , $ tableName = null , $ connectionName = null ) { if ( ! is_array ( $ columnNames ) ) { $ columnNames = [ $ columnNames ] ; } $ tableName = $ this -> validateTableName ( $ tableName ) ; $ indexes = $ this -> getTableIndexes ( $ tableName , $ connectionName ) ; foreach ( $ indexes as $ index ) { $ indexColumns = $ index -> getColumns ( ) ; if ( count ( $ indexColumns ) === count ( $ columnNames ) && count ( $ indexColumns ) === count ( array_intersect ( $ indexColumns , $ columnNames ) ) ) { return $ index ; } } return false ; }
Get index by columns name
35,649
public function getTableColumns ( $ tableName = null , $ connectionName = null ) { $ tableName = $ this -> validateTableName ( $ tableName ) ; return $ this -> getSchema ( $ connectionName ) -> listTableColumns ( $ tableName ) ; }
Get table columns information
35,650
public function getTableForeignKeys ( $ tableName = null , $ connectionName = null ) { $ tableName = $ this -> validateTableName ( $ tableName ) ; return $ this -> getSchema ( $ connectionName ) -> listTableForeignKeys ( $ tableName ) ; }
Get table foreign key information
35,651
public function getForeignTableNames ( $ tableName = null , $ connectionName = null ) { $ foreignKeys = $ this -> getTableForeignKeys ( $ tableName , $ connectionName ) ; $ tableNames = [ ] ; foreach ( $ foreignKeys as $ foreignKey ) { $ tableNames [ ] = $ foreignKey -> getForeignTableName ( ) ; } return array_unique ( $ tableNames ) ; }
Get tables foreign table names from foreign keys
35,652
protected function getTableIndexes ( $ tableName = null , $ connectionName = null ) { $ tableName = $ this -> validateTableName ( $ tableName ) ; return $ this -> getSchema ( $ connectionName ) -> listTableIndexes ( $ tableName ) ; }
Get table indexes
35,653
protected function validateTableName ( $ tableName = null ) { $ tableName = $ tableName === null ? $ this -> tableName : $ tableName ; if ( $ tableName === null ) { throw new DbExporterException ( 'Table name is null' ) ; } return $ tableName ; }
Validate table name in parameter and in class property
35,654
protected function serializeArrayToAttributes ( $ attributes , $ forceArray = false ) { if ( ! is_array ( $ attributes ) ) { $ attributes = [ $ attributes ] ; } foreach ( $ attributes as & $ attribute ) { $ attribute = str_replace ( [ 'ID' ] , [ 'Id' ] , $ attribute ) ; $ attribute = '\'' . snake_case ( $ attribute ) . '\'' ; } return $ forceArray || count ( $ attributes ) > 1 ? '[' . implode ( ', ' , $ attributes ) . ']' : reset ( $ attributes ) ; }
If array contains only one element return exported array value otherwise return serialized array of elements
35,655
protected function serializeIndexNameToAttribute ( $ indexName ) { if ( strtolower ( $ indexName ) === 'primary' ) { $ indexName = 'prim' ; } $ indexName = str_replace ( [ 'ID' ] , [ 'Id' ] , $ indexName ) ; return '\'' . snake_case ( $ indexName ) . '\'' ; }
Serialize index name to pass as attribute
35,656
protected function skipTable ( $ tableName ) { if ( count ( $ this -> option ( 'select' ) ) > 0 && ! in_array ( $ tableName , $ this -> option ( 'select' ) , true ) ) { return true ; } if ( in_array ( $ tableName , $ this -> option ( 'ignore' ) , true ) ) { return true ; } return false ; }
Check if table is selected or not
35,657
protected function makeAppAddon ( $ path ) { $ config = [ 'namespace' => trim ( $ this -> getAppNamespace ( ) , '\\' ) , ] ; return new Addon ( null , 'app' , $ path , $ config ) ; }
Make addon instance for application namespace .
35,658
public function get ( $ force = false ) { if ( is_null ( self :: $ current ) || $ force ) { $ releaseStage = trim ( getenv ( 'RELEASE_STAGE' ) ) ; $ releaseStage = in_array ( $ releaseStage , $ this -> getAll ( ) ) ? $ releaseStage : null ; $ releaseStage = $ releaseStage ? : $ this -> determineFromPath ( ) ; $ releaseStage = $ releaseStage ? : $ this -> detectAppServer ( ) ; $ releaseStage = $ releaseStage ? : self :: PRODUCTION ; self :: $ current = $ releaseStage ; } return self :: $ current ; }
Get release stage
35,659
public function getAll ( ) { return array ( self :: DEVELOPMENT => self :: DEVELOPMENT , self :: TESTING => self :: TESTING , self :: STAGING => self :: STAGING , self :: PRODUCTION => self :: PRODUCTION , ) ; }
Get all release stages
35,660
public function determineFromPath ( ) { $ releaseStage = null ; $ httpHost = isset ( $ _SERVER [ 'HTTP_HOST' ] ) ? $ _SERVER [ 'HTTP_HOST' ] : '' ; $ documentRoot = isset ( $ _SERVER [ 'DOCUMENT_ROOT' ] ) ? $ _SERVER [ 'DOCUMENT_ROOT' ] : '' ; $ paths = __DIR__ . $ httpHost . $ documentRoot ; if ( strpos ( $ paths , 'stage' ) !== false || strpos ( $ paths , 'staging' ) !== false ) { $ releaseStage = self :: STAGING ; } elseif ( strpos ( __FILE__ , '/home' ) !== false && strpos ( __FILE__ , 'vhosts' ) !== false ) { $ releaseStage = self :: DEVELOPMENT ; } elseif ( substr ( $ httpHost , - 6 ) == '.local' || substr ( $ httpHost , - 4 ) == '.dev' ) { $ releaseStage = self :: DEVELOPMENT ; } return $ releaseStage ; }
Determine the current environment based on the path
35,661
public function sortBy ( $ field , $ order = 'ASC' ) { Argument :: i ( ) -> test ( 1 , 'string' ) -> test ( 2 , 'string' ) ; $ this -> sortBy [ ] = $ field . ' ' . $ order ; return $ this ; }
Order by clause
35,662
public function remove ( $ params = [ ] ) { $ this -> params = array_diff_key ( $ this -> params , array_fill_keys ( $ params , '' ) ) ; return $ this ; }
Remove url params
35,663
public function checkPageBreak ( $ h = 0 , $ y = '' , $ addpage = true ) { return parent :: checkPageBreak ( $ h , $ y , $ addpage ) ; }
Add page if needed .
35,664
protected function unserializeType ( $ value , $ type ) { if ( $ type === self :: TYPE_JSON ) { if ( $ value === null ) { return null ; } elseif ( $ value === '' ) { return new \ stdClass ( ) ; } elseif ( is_resource ( $ value ) ) { $ value = stream_get_contents ( $ value ) ; } return json_decode ( $ value ) ; } else { return $ this -> connection -> convertToPHPValue ( $ value , TypeMapper :: getDoctrineTypeByType ( $ type ) ) ; } }
Returns a php type based on the serialized string representation
35,665
protected function serializeType ( $ value , $ type ) { return $ this -> connection -> convertToDatabaseValue ( $ value , TypeMapper :: getDoctrineTypeByType ( $ type ) ) ; }
Returns a string representation which can be stored in the database
35,666
public function createNotification ( $ format , $ alert , array $ options = [ ] , $ tagsOrTagExpression = '' , \ DateTime $ scheduleTime = null ) { $ class = __NAMESPACE__ . '\\' . ucfirst ( $ format ) . 'Notification' ; if ( ! class_exists ( $ class ) ) { throw new \ RuntimeException ( 'Invalid format: ' . $ format ) ; } return new $ class ( $ alert , $ options , $ tagsOrTagExpression , $ scheduleTime ) ; }
Creates the Notification class according to the format .
35,667
public function respondTo ( $ responses ) { $ format = $ this -> request ( ) -> format ( ) ; foreach ( $ responses as $ fmt => $ action ) { if ( is_int ( $ fmt ) ) { $ fmt = $ action ; $ action = null ; } if ( $ fmt !== $ format ) continue ; if ( $ action ) { if ( ! $ action instanceof Closure ) { throw new Exception \ InvalidArgumentException ( sprinft ( 'Only closure can be passed to respondTo, %s passed' , gettype ( $ action ) ) ) ; } $ action ( ) ; } else { $ action = true ; } $ this -> _respond_action = $ action ; return ; } Rails :: log ( ) -> message ( "406 Not Acceptable" ) ; $ this -> render ( array ( 'nothing' => true ) , array ( 'status' => 406 ) ) ; }
Respond to format
35,668
public function layout ( $ value = null ) { if ( null === $ value ) return $ this -> layout ; else $ this -> layout = $ value ; }
Sets layout value .
35,669
private function _view_file_exists ( ) { $ route = Rails :: application ( ) -> dispatcher ( ) -> router ( ) -> route ( ) ; $ base_path = Rails :: config ( ) -> paths -> views ; $ view_path = $ base_path . '/' . $ route -> path ( ) . '.php' ; return is_file ( $ view_path ) ; }
If the method for the requested action doesn t exist in the controller it s checked if the view file exists .
35,670
private function run_initializers ( ) { $ method_name = 'init' ; $ cn = get_called_class ( ) ; if ( $ inits = $ this -> getAppControllersMethod ( $ method_name ) ) { foreach ( $ inits as $ init ) { $ init = $ init -> bindTo ( $ this ) ; $ init ( ) ; } } $ method = $ this -> selfRefl -> getMethod ( $ method_name ) ; if ( $ method -> getDeclaringClass ( ) -> getName ( ) == $ cn ) { $ this -> $ method_name ( ) ; } }
Runs initializers for both the actual controller class and it s parent ApplicationController if any .
35,671
public function createRequestsForGroups ( array $ groups ) { foreach ( $ groups as $ group ) { array_push ( $ this -> createdRequests , new Request ( 'GET' , $ group -> types -> href ) ) ; } }
Creates a set of requests .
35,672
public function fetchGroupsInfromation ( $ rejectedCallbackFunction ) { $ pool = new Pool ( $ this -> client , $ this -> createdRequests , [ 'concurrency' => 18 , 'fulfilled' => function ( $ response , $ index ) { $ responseJson = json_decode ( $ response -> getBody ( ) -> getContents ( ) ) ; $ groupPagesIterator = new MarketGroupsPagesIterator ( $ responseJson , $ this -> client ) ; $ this -> acceptedResponses [ $ index ] = iterator_to_array ( $ groupPagesIterator -> getAllPages ( ) ) ; } , 'rejected' => function ( $ reason , $ index ) use ( & $ rejectedCallbackFunction ) { call_user_func_array ( $ rejectedCallbackFunction , array ( $ reason , $ index ) ) ; } , ] ) ; $ promise = $ pool -> promise ( ) ; $ promise -> wait ( ) ; }
Uses the Guzzel Pool to process Requests .
35,673
public function getGroupInformationContainer ( array $ acceptedResponses , array $ groups ) { if ( count ( $ acceptedResponses ) > 0 ) { foreach ( $ groups as $ index => $ group ) { if ( isset ( $ acceptedResponses [ $ index ] ) ) { $ this -> groupInformationContainer [ $ group -> name ] = $ acceptedResponses [ $ index ] ; } } return $ this -> groupInformationContainer ; } else { return false ; } }
Returns Either False or a container .
35,674
public function selectDatabase ( $ database ) { $ mysqli = $ this -> _mysqli ( ) ; if ( ! $ mysqli -> select_db ( $ database ) ) throw new Exception ( $ mysqli -> error , $ mysqli -> errno ) ; $ this -> _selectedDatabase = $ database ; return $ this ; }
Selects a particular database
35,675
private function _mysqli ( ) { if ( ! isset ( $ this -> _link ) ) { mysqli_report ( MYSQLI_REPORT_OFF ) ; if ( ! $ this -> _link = mysqli_init ( ) ) throw new Exception ( "Mysql initialization failed" ) ; $ sqlMode = $ this -> _strict ? 'TRADITIONAL' : '' ; $ this -> _link -> options ( MYSQLI_INIT_COMMAND , "SET SESSION sql_mode = '{$sqlMode}'" ) ; $ this -> _link -> options ( MYSQLI_OPT_CONNECT_TIMEOUT , 5 ) ; @ $ this -> _link -> real_connect ( $ this -> _dsn -> host , $ this -> _dsn -> user , $ this -> _dsn -> pass , $ this -> _dsn -> database , $ this -> _dsn -> port ) ; if ( $ this -> _link -> connect_error ) throw new Exception ( "Failed to connect to mysql: {$this->_link->connect_error}" , $ this -> _link -> connect_errno ) ; if ( ! $ this -> _link -> set_charset ( $ this -> _charset ) ) throw new Exception ( sprintf ( "Error setting character to %s: %s" , $ this -> _charset , $ this -> _link -> error ) ) ; } return $ this -> _link ; }
Lazily creates the internal mysqli object
35,676
public function execute ( $ sql , $ params = array ( ) ) { if ( ! is_array ( $ params ) ) $ params = array_slice ( func_get_args ( ) , 1 ) ; $ mysqli = $ this -> _mysqli ( ) ; $ debug = $ this -> _debug ; $ sql = count ( $ params ) ? $ this -> binder ( ) -> bind ( $ sql , $ params ) : $ sql ; return $ this -> _filter -> execute ( $ sql , function ( $ sql ) use ( $ mysqli , $ debug ) { \ Pheasant \ Database \ Mysqli \ Connection :: $ counter ++ ; if ( $ debug ) { $ timer = microtime ( true ) ; } $ r = $ mysqli -> query ( $ sql , MYSQLI_STORE_RESULT ) ; if ( $ debug ) { \ Pheasant \ Database \ Mysqli \ Connection :: $ timer += microtime ( true ) - $ timer ; } if ( $ debug ) { printf ( "<pre>Pheasant executed <code>%s</code> on thread #%d in %.2fms, returned %d rows</pre>\n\n" , $ sql , $ mysqli -> thread_id , ( microtime ( true ) - $ timer ) * 1000 , is_object ( $ r ) ? $ r -> num_rows : 0 ) ; } if ( $ mysqli -> error ) { if ( $ mysqli -> errno === 1213 || $ mysqli -> errno === 1479 ) { throw new DeadlockException ( $ mysqli -> error , $ mysqli -> errno ) ; } else { throw new Exception ( $ mysqli -> error , $ mysqli -> errno ) ; } } return new ResultSet ( $ mysqli , $ r === true ? false : $ r ) ; } ) ; }
Executes a statement
35,677
public function callback ( $ callback ) { $ t = $ this ; $ args = array_slice ( func_get_args ( ) , 1 ) ; $ this -> _events -> register ( 'startTransaction' , function ( $ event , $ connection ) use ( $ t , $ callback , $ args ) { $ t -> results [ ] = call_user_func_array ( $ callback , $ args ) ; } ) ; return $ this ; }
Adds a callback that gets passed any extra varargs as a arguments
35,678
public static function create ( $ closure , $ execute = true ) { $ transaction = new self ( ) ; $ transaction -> callback ( $ closure ) ; if ( $ execute ) $ transaction -> execute ( ) ; return $ transaction ; }
Creates a transaction and optionally execute a transaction
35,679
public function create ( OptionsBag $ sessionOptions ) { $ options = $ this -> parseOptions ( $ sessionOptions ) ; $ connections = $ this -> parse ( $ sessionOptions ) ; $ persistentId = null ; if ( $ options [ 'persistent' ] ) { $ persistentId = $ this -> parsePersistentId ( $ connections , $ options , $ sessionOptions ) ; } $ class = $ this -> class ; $ memcached = new $ class ( $ persistentId , function ( Memcached $ memcached ) use ( $ connections , $ options ) { $ this -> configure ( $ memcached , $ connections , $ options ) ; } ) ; return $ memcached ; }
Creates a Memcached instance from the session options .
35,680
protected function configure ( Memcached $ memcached , array $ connections , OptionsBag $ options ) { $ binary = $ options -> getBoolean ( 'binary_protocol' ) ; $ needsAuth = $ options -> get ( 'username' ) && $ options -> get ( 'password' ) ; if ( $ needsAuth ) { $ binary = true ; if ( ! constant ( $ this -> class . '::HAVE_SASL' ) ) { throw new RuntimeException ( 'memcached extension needs to be built with SASL support to use username and password' ) ; } } $ memcached -> setOptions ( [ Memcached :: OPT_BINARY_PROTOCOL => $ binary , Memcached :: OPT_LIBKETAMA_COMPATIBLE => $ options -> getBoolean ( 'consistent_hash' ) , Memcached :: OPT_SERVER_FAILURE_LIMIT => $ options -> getInt ( 'server_failure_limit' , 1 ) , Memcached :: OPT_NUMBER_OF_REPLICAS => $ options -> getInt ( 'number_of_replicas' ) , Memcached :: OPT_RANDOMIZE_REPLICA_READ => $ options -> getBoolean ( 'randomize_replica_read' ) , Memcached :: OPT_REMOVE_FAILED_SERVERS => $ options -> getBoolean ( 'remove_failed_servers' ) , Memcached :: OPT_CONNECT_TIMEOUT => $ options -> getInt ( 'connect_timeout' ) , ] ) ; if ( $ needsAuth ) { $ memcached -> setSaslAuthData ( $ options -> get ( 'username' ) , $ options -> get ( 'password' ) ) ; } foreach ( $ connections as $ conn ) { $ memcached -> addServer ( $ conn [ 'host' ] , $ conn [ 'port' ] , $ conn [ 'weight' ] ) ; } }
Configure a new Memcached instance . This isn t needed for existing persisted connections .
35,681
protected function parseOptions ( OptionsBag $ sessionOptions ) { $ options = new OptionsBag ( $ sessionOptions -> get ( 'options' , [ ] ) ) ; $ iniKeys = [ 'persistent' => 'bool' , 'binary_protocol' => 'bool' , 'consistent_hash' => 'bool' , 'server_failure_limit' => 'int' , 'remove_failed_servers' => 'bool' , 'randomize_replica_read' => 'bool' , 'number_of_replicas' => 'int' , 'connect_timeout' => 'int' , 'sasl_username' => 'string' , 'sasl_password' => 'string' , 'prefix' => 'string' , ] ; $ v2IniKeys = [ 'remove_failed_servers' => [ 'remove_failed' , 'bool' ] , 'binary_protocol' => [ 'binary' , 'bool' ] , ] ; foreach ( $ v2IniKeys as $ new => list ( $ old , $ type ) ) { if ( $ options -> has ( $ old ) ) { Deprecated :: warn ( "Memcached option \"$old\"" , 1.0 , "Use \"$new\" instead." ) ; if ( ! $ options -> has ( $ new ) ) { $ options -> set ( $ new , $ options -> get ( $ old ) ) ; } $ options -> remove ( $ old ) ; } } foreach ( $ iniKeys as $ key => $ type ) { if ( ! $ options -> has ( $ key ) && $ this -> ini -> has ( $ key ) ) { if ( $ type === 'bool' ) { $ value = $ this -> ini -> getBoolean ( $ key ) ; } elseif ( $ type === 'int' ) { $ value = $ this -> ini -> getInt ( $ key ) ; } else { $ value = $ this -> ini -> get ( $ key ) ; } $ options [ $ key ] = $ value ; } } foreach ( $ v2IniKeys as $ new => list ( $ old , $ type ) ) { if ( ! $ options -> has ( $ new ) && $ this -> ini -> has ( $ old ) ) { if ( $ type === 'bool' ) { $ value = $ this -> ini -> getBoolean ( $ old ) ; } elseif ( $ type === 'int' ) { $ value = $ this -> ini -> getInt ( $ old ) ; } else { $ value = $ this -> ini -> get ( $ old ) ; } $ options [ $ new ] = $ value ; } } if ( ! $ options -> has ( 'username' ) ) { $ options [ 'username' ] = $ options -> get ( 'sasl_username' ) ; } if ( ! $ options -> has ( 'password' ) ) { $ options [ 'password' ] = $ options -> get ( 'sasl_password' ) ; } $ options -> remove ( 'sasl_username' ) ; $ options -> remove ( 'sasl_password' ) ; return $ options ; }
Parse Memcached options from session options and from ini .
35,682
protected function parsePersistentId ( array $ connections , OptionsBag $ options , OptionsBag $ sessionOptions ) { $ savePath = $ sessionOptions [ 'save_path' ] ; $ savePath = trim ( $ savePath ) ; if ( $ savePath ) { $ persistentId = 'memc-session:' . $ savePath ; if ( strpos ( $ savePath , 'PERSISTENT=' ) === 0 ) { $ end = strpos ( $ savePath , ' ' ) ; if ( $ end === false ) { throw new InvalidArgumentException ( 'Unable to parse session save_path' ) ; } $ persistentId = substr ( $ savePath , 11 , $ end - 11 ) ; } return $ persistentId ; } if ( $ options -> has ( 'persistent_id' ) ) { return $ options [ 'persistent_id' ] ; } $ hashParts = [ ] ; foreach ( $ connections as $ conn ) { $ hashParts [ ] = sprintf ( '%s:%s:%s' , $ conn [ 'host' ] , $ conn [ 'port' ] , $ conn [ 'weight' ] ) ; } foreach ( $ options as $ key => $ value ) { $ hashParts [ ] = $ key . ':' . $ value ; } $ hash = hash ( 'sha256' , implode ( ',' , $ hashParts ) ) ; return $ hash ; }
Parse the Persistent ID from save_path and sets it on options .
35,683
protected function getMethodCallsForForeignKeys ( ) { $ methods = [ ] ; if ( $ keys = $ this -> getForeignKeys ( ) ) { foreach ( $ keys as $ key ) { $ relatedTable = $ key -> getRelatedTable ( ) ; $ relatedModel = '\\' . $ this -> getAppNamespace ( ) . $ relatedTable -> getModelName ( ) . '::class' ; if ( $ key -> isSource ( ) ) { $ methodName = lcfirst ( $ key -> isForMany ( ) ? $ relatedTable -> getName ( ) : $ relatedTable -> getModelName ( ) ) ; $ methodReturnSuffix = 'has' . ( $ key -> isForMany ( ) ? 'Many' : 'One' ) ; $ methodContent = "return \$this->{$methodReturnSuffix}({$relatedModel});" ; } elseif ( $ key -> isForPivotTable ( ) ) { $ methodName = lcfirst ( $ key -> isForMany ( ) && $ key -> isForPivotTable ( ) ? $ relatedTable -> getName ( ) : $ relatedTable -> getModelName ( ) ) ; $ methodReturnSuffix = 'belongsToMany' ; $ methodContent = "return \$this->{$methodReturnSuffix}({$relatedModel});" ; } else { $ methodName = lcfirst ( $ key -> isForMany ( ) && $ key -> isForPivotTable ( ) ? $ relatedTable -> getName ( ) : $ relatedTable -> getModelName ( ) ) ; $ methodReturnSuffix = 'belongsTo' ; $ methodContent = "return \$this->{$methodReturnSuffix}({$relatedModel}, '{$key->foreign}');" ; } $ methodName = preg_replace_callback ( '/(_[a-z])/' , function ( $ matches ) { return strtoupper ( substr ( $ matches [ 0 ] , 1 ) ) ; } , $ methodName ) ; $ method = "\t/**\n\t * Getter for {$relatedTable->getName()}.\n\t " . "* @return \\Illuminate\\Database\\Eloquent\\Relations\\" . ucfirst ( $ methodReturnSuffix ) . " \n\t */\n\t" . "public function {$methodName}()\n\t{\n\t\t{$methodContent}\n\t}" ; $ methods [ ] = $ method ; } } return array_unique ( $ methods ) ; }
Returns the parsed method calls for the foreign keys .
35,684
protected function parsePropertyValue ( $ value ) { $ return = '' ; if ( is_array ( $ value ) ) { $ withStringIndex = ( bool ) array_filter ( array_keys ( $ value ) , 'is_string' ) ; if ( $ withStringIndex ) { $ return = preg_replace ( [ '/^(array ?\( *)/' , '/\)$/' ] , [ '[' , ']' ] , str_replace ( "\n" , '' , var_export ( $ value , true ) ) ) ; } else { $ return = '[' . rtrim ( array_reduce ( $ value , function ( $ combined , $ single ) { return $ combined . var_export ( $ single , true ) . ', ' ; } , '' ) , ', ' ) . ']' ; } } else { $ return = var_export ( $ value , true ) ; } return $ return ; }
Parses the given value to an exportable php code .
35,685
public function save ( $ inPlaceholder = " //" ) { if ( ! file_exists ( $ modelFile = app_path ( $ target = $ this -> getTargetModel ( ) . '.php' ) ) ) { throw new LogicException ( sprintf ( 'Model %s not found' , $ target ) ) ; } $ this -> writeToModel ( $ modelFile , $ inPlaceholder ) ; return true ; }
Saves the properties in the placeholder .
35,686
protected function writeToModel ( $ modelFile , $ inPlaceholder = " //" ) { $ replaces = [ ] ; $ searches = [ ] ; foreach ( $ this -> getProperties ( ) as $ property => $ content ) { $ replaces [ ] = $ this -> parsePropertyValue ( $ content ) ; $ searches [ ] = '{{' . $ property . '}}' ; } $ methodContent = '' ; $ newContent = str_replace ( $ searches , $ replaces , file_get_contents ( realpath ( __DIR__ . '/stubs/model-content.stub' ) ) ) ; if ( $ keys = $ this -> getForeignKeys ( ) ) { $ methodContent = implode ( "\n\n" , $ this -> getMethodCallsForForeignKeys ( ) ) ; } $ newContent = str_replace ( [ " // {{relations}}" , '// {{traits}}' ] , [ $ methodContent , ( $ traits = $ this -> getTraits ( ) ) ? 'use ' . implode ( ', ' , $ traits ) . ';' : '' ] , $ newContent ) ; $ written = file_put_contents ( $ modelFile , str_replace ( $ inPlaceholder , $ newContent , file_get_contents ( $ modelFile ) ) ) ; if ( $ written ) { if ( DIRECTORY_SEPARATOR === '\\' ) { $ exec = ".\\vendor\\bin\\phpcbf.bat {$modelFile} --standard=PSR2" ; } else { $ exec = "vendor/bin/phpcbf {$modelFile} --standard=PSR2" ; } @ exec ( $ exec , $ output , $ return ) ; } return $ written ; }
Writes the stub properties to the target model .
35,687
public function addAccountPurchases ( $ accountPurchases ) { if ( ! $ accountPurchases ) { return ; } foreach ( $ accountPurchases as $ accountPurchase ) { $ accountId = $ accountPurchase [ 'account' ] [ 'id' ] ; if ( ! array_key_exists ( $ accountId , $ this -> customerSupplierItems ) ) { continue ; } $ customerData = [ ] ; if ( isset ( $ accountPurchase [ 'avisoContact' ] ) ) { $ customerData [ 'avisoContact' ] = $ accountPurchase [ 'avisoContact' ] ; } if ( isset ( $ accountPurchase [ 'contact' ] ) ) { $ customerData [ 'contact' ] = $ accountPurchase [ 'contact' ] ; } $ this -> customerSupplierItems [ $ accountId ] = $ this -> customerSupplierItems [ $ accountId ] + $ customerData ; } }
Adds extra customer data to customerSupplierItems .
35,688
public function toArray ( ) { return [ 'title' => $ this -> title , 'description' => $ this -> description , 'commission' => $ this -> commission , 'costCentre' => $ this -> costCentre , 'currencyCode' => $ this -> currencyCode , 'netShippingCosts' => $ this -> netShippingCosts , 'internalNote' => $ this -> getInternalNote ( ) , 'responsibleContact' => $ this -> createDataArray ( $ this -> responsibleContact ) , 'items' => $ this -> itemsToArray ( ) , ] ; }
Converts TransitionData to array .
35,689
public function map ( ) { $ map = config ( 'db-exporter.model.map' ) ; foreach ( $ map as $ item ) { $ tablePattern = '/' . str_replace ( '/' , '\/' , $ item [ 'tablePattern' ] ) . '/' ; if ( preg_match ( $ tablePattern , $ this -> table -> getTableName ( ) ) === 1 ) { $ this -> path = $ item [ 'path' ] ; $ this -> namespace = $ item [ 'namespace' ] ; if ( $ item [ 'className' ] !== null ) { $ pattern = '/' . str_replace ( '/' , '\/' , $ item [ 'className' ] [ 'pattern' ] ) . '/' ; $ replacement = $ item [ 'className' ] [ 'replacement' ] ; echo $ replacement ; $ this -> class = preg_replace ( $ pattern , $ replacement , $ this -> class ) ; } break ; } } }
Apply custom config map settings if pattern exists
35,690
public function writeOut ( OutputInterface $ output = null , $ force = false ) { $ class = str_singular ( $ this -> getClass ( ) ) ; $ this -> writeToFileFromTemplate ( $ this -> path . '/' . $ class . '.php' , 'model' , $ output , [ 'namespace' => $ this -> namespace , 'className' => $ class , 'tableName' => snake_case ( $ this -> table -> getTableName ( ) ) , 'relationMethods' => $ this -> table -> renderRelationMethods ( ) , ] , $ force ) ; }
Render model class and write out to file
35,691
protected function getFileContent ( Content $ content ) { $ text = @ file_get_contents ( $ this -> contentPath . $ content -> getPath ( ) ) ; if ( null === $ this -> getContentPath ( ) ) { throw new ConfigurationException ( 'ContentPath is not set. Call setContentPath before reading a file content.' ) ; } if ( false === $ text ) { throw new RenderException ( 'Unable to read: ' . $ content -> getPath ( ) . '. Full path: ' . ( $ this -> getContentPath ( ) . $ content -> getPath ( ) ) ) ; } return $ text ; }
Reads a file content of Content object
35,692
private function getCurrencies ( ) { $ currencies = $ this -> get ( 'sulu_product.currency_repository' ) -> findBy ( [ ] , [ 'name' => 'asc' ] ) ; $ currencyValues = array ( ) ; foreach ( $ currencies as $ currency ) { $ currencyValues [ ] = array ( 'id' => $ currency -> getId ( ) , 'name' => $ currency -> getName ( ) , 'code' => $ currency -> getCode ( ) ) ; } return $ currencyValues ; }
Returns all currencies .
35,693
private function getTaxClasses ( $ locale ) { $ itemManager = $ this -> get ( 'sulu_sales_core.item_manager' ) ; $ taxClasses = $ this -> get ( 'sulu_product.tax_class_repository' ) -> findAll ( ) ; $ result = [ ] ; foreach ( $ taxClasses as $ taxClass ) { $ result [ ] = [ 'id' => $ taxClass -> getId ( ) , 'name' => $ taxClass -> getTranslation ( $ locale ) -> getName ( ) , 'tax' => $ itemManager -> retrieveTaxForClass ( $ taxClass ) ] ; } return $ result ; }
Returns all tax classes .
35,694
private function getProductUnits ( $ locale ) { $ productUnits = $ this -> get ( 'sulu_product.unit_repository' ) -> findAllByLocale ( $ locale ) ; $ result = [ ] ; foreach ( $ productUnits as $ productUnit ) { $ result [ ] = [ 'id' => $ productUnit -> getId ( ) , 'name' => $ productUnit -> getTranslation ( $ locale ) -> getName ( ) , ] ; } return $ result ; }
Returns all product units .
35,695
public function create ( OptionsBag $ sessionOptions ) { $ connections = $ this -> parse ( $ sessionOptions ) ; $ conn = $ this -> selectConnection ( $ connections ) ; $ class = $ this -> class ; $ redis = new $ class ( ) ; return $ this -> configure ( $ redis , $ conn ) ; }
Creates a Redis instance from the session options .
35,696
public function configure ( Redis $ redis , OptionsBag $ conn ) { if ( $ conn [ 'persistent' ] ) { $ redis -> pconnect ( $ conn [ 'host' ] , $ conn [ 'port' ] , $ conn [ 'timeout' ] ) ; } else { $ redis -> connect ( $ conn [ 'host' ] , $ conn [ 'port' ] , $ conn [ 'timeout' ] , $ conn [ 'retry_interval' ] ) ; } if ( $ conn [ 'password' ] ) { $ redis -> auth ( $ conn [ 'password' ] ) ; } if ( $ conn [ 'database' ] >= 0 ) { $ redis -> select ( $ conn [ 'database' ] ) ; } if ( $ conn [ 'prefix' ] ) { $ redis -> setOption ( Redis :: OPT_PREFIX , $ conn [ 'prefix' ] ) ; } return $ redis ; }
Configure the Redis instance with the parsed connection parameters .
35,697
public function selectConnection ( array $ connections ) { $ weighted = [ ] ; foreach ( $ connections as $ connection ) { foreach ( range ( 0 , $ connection [ 'weight' ] ) as $ i ) { $ weighted [ ] = $ connection ; } } $ index = mt_rand ( 0 , count ( $ weighted ) - 1 ) ; return $ weighted [ $ index ] ; }
Select connection randomly accounting for weight .
35,698
public function getter ( $ key ) { $ property = $ this ; return function ( $ object ) use ( $ key , $ property ) { $ value = $ object -> get ( $ key ) ; if ( is_null ( $ value ) && $ property -> type -> options ( ) -> primary ) { return $ property -> reference ( $ object ) ; } else { return $ value ; } } ; }
Return a closure for accessing the value of the property
35,699
public function resetUserConfig ( UsersListener $ listener , User $ user ) { try { $ this -> userConfigRepository -> deleteByUserId ( $ user -> id ) ; return $ listener -> resetSuccess ( ) ; } catch ( Exception $ e ) { Log :: emergency ( $ e -> getMessage ( ) ) ; return $ listener -> resetFailed ( ) ; } }
Reset configuration for given user for all providers . Response will be returned .