idx int64 0 60.3k | question stringlengths 99 4.85k | target stringlengths 5 718 |
|---|---|---|
200 | protected function createRelatedEntities ( $ relations ) { $ entitiesToCreate = $ this -> aggregate -> getNonExistingRelated ( $ relations ) ; foreach ( $ entitiesToCreate as $ aggregate ) { $ this -> createStoreCommand ( $ aggregate ) -> execute ( ) ; } } | Check for existence and create non - existing related entities . |
201 | protected function createStoreCommand ( Aggregate $ aggregate ) : self { $ mapper = $ aggregate -> getMapper ( ) ; return new self ( $ aggregate , $ mapper -> newQueryBuilder ( ) ) ; } | Create a new store command . |
202 | protected function postStoreProcess ( ) { $ aggregate = $ this -> aggregate ; $ foreignRelationships = $ aggregate -> getEntityMap ( ) -> getForeignRelationships ( ) ; $ this -> createRelatedEntities ( $ foreignRelationships ) ; $ aggregate -> updatePivotRecords ( ) ; $ dirtyRelatedAggregates = $ aggregate -> getDirtyRelationships ( ) ; foreach ( $ dirtyRelatedAggregates as $ related ) { $ this -> createStoreCommand ( $ related ) -> execute ( ) ; } if ( $ this -> aggregate -> exists ( ) ) { $ this -> aggregate -> syncRelationships ( $ foreignRelationships ) ; } $ aggregate -> setProxies ( ) ; $ aggregate -> getMapper ( ) -> getEntityCache ( ) -> refresh ( $ aggregate ) ; } | Run all operations that have to occur after the entity is stored . |
203 | protected function insert ( ) { $ aggregate = $ this -> aggregate ; $ attributes = $ aggregate -> getRawAttributes ( ) ; $ keyName = $ aggregate -> getEntityMap ( ) -> getKeyName ( ) ; if ( array_key_exists ( $ keyName , $ attributes ) && $ attributes [ $ keyName ] != null ) { $ this -> query -> insert ( $ attributes ) ; } else { if ( array_key_exists ( $ keyName , $ attributes ) ) { unset ( $ attributes [ $ keyName ] ) ; } if ( isset ( $ attributes [ 'attributes' ] ) ) { unset ( $ attributes [ 'attributes' ] ) ; } $ id = $ this -> query -> insertGetId ( $ attributes , $ keyName ) ; $ aggregate -> setEntityAttribute ( $ keyName , $ id ) ; } } | Execute an insert statement on the database . |
204 | protected function syncForeignKeyAttributes ( ) { $ attributes = $ this -> aggregate -> getForeignKeyAttributes ( ) ; foreach ( $ attributes as $ key => $ value ) { $ this -> aggregate -> setEntityAttribute ( $ key , $ value ) ; } } | Update attributes on actual entity . |
205 | protected function update ( ) { $ key = $ this -> aggregate -> getEntityKeyName ( ) ; $ value = $ this -> aggregate -> getEntityKeyValue ( ) ; $ this -> query -> where ( $ key , $ value ) ; $ dirtyAttributes = $ this -> aggregate -> getDirtyRawAttributes ( ) ; if ( count ( $ dirtyAttributes ) > 0 ) { $ this -> query -> update ( $ dirtyAttributes ) ; } } | Run an update statement on the entity . |
206 | public function add ( $ entity , string $ id ) { $ entityClass = get_class ( $ entity ) ; if ( $ entityClass !== $ this -> class ) { throw new CacheException ( 'Tried to cache an instance with a wrong type : expected ' . $ this -> class . ", got $entityClass" ) ; } if ( ! $ this -> has ( $ id ) ) { $ this -> instances [ $ id ] = $ entity ; } } | Add an entity to the cache . |
207 | protected function registerSoftDelete ( Mapper $ mapper ) { $ entityMap = $ mapper -> getEntityMap ( ) ; $ mapper -> addGlobalScope ( new SoftDeletingScope ( ) ) ; $ mapper -> registerEvent ( 'deleting' , function ( $ event ) use ( $ entityMap ) { $ entity = $ event -> entity ; $ wrappedEntity = $ this -> getMappable ( $ entity ) ; $ deletedAtField = $ entityMap -> getQualifiedDeletedAtColumn ( ) ; if ( ! is_null ( $ wrappedEntity -> getEntityAttribute ( $ deletedAtField ) ) ) { return true ; } $ time = new Carbon ( ) ; $ wrappedEntity -> setEntityAttribute ( $ deletedAtField , $ time ) ; $ plainObject = $ wrappedEntity -> getObject ( ) ; $ this -> manager -> mapper ( get_class ( $ plainObject ) ) -> store ( $ plainObject ) ; return false ; } ) ; $ mapper -> addCustomCommand ( Restore :: class ) ; } | By hooking to the mapper initialization event we can extend it with the softDelete capacity . |
208 | public function execute ( ) { $ aggregate = $ this -> aggregate ; $ entity = $ aggregate -> getEntityObject ( ) ; $ wrappedEntity = $ aggregate -> getWrappedEntity ( ) ; $ mapper = $ aggregate -> getMapper ( ) ; if ( $ mapper -> fireEvent ( 'deleting' , $ wrappedEntity ) === false ) { return false ; } $ keyName = $ aggregate -> getEntityMap ( ) -> getKeyName ( ) ; $ id = $ this -> aggregate -> getEntityKeyValue ( ) ; if ( is_null ( $ id ) ) { throw new MappingException ( 'Executed a delete command on an entity with "null" as primary key' ) ; } $ this -> query -> where ( $ keyName , '=' , $ id ) -> delete ( ) ; $ mapper -> fireEvent ( 'deleted' , $ wrappedEntity , false ) ; } | Execute the Delete Statement . |
209 | public function initializeProxy ( ) : bool { if ( $ this -> isProxyInitialized ( ) ) { return true ; } $ this -> items = $ this -> prependedItems + $ this -> getRelationshipInstance ( ) -> getResults ( $ this -> relationshipMethod ) -> all ( ) + $ this -> pushedItems ; $ this -> relationshipLoaded = true ; return true ; } | Force initialization of the proxy . |
210 | protected function getRelationshipInstance ( ) : Relationship { $ relation = $ this -> relationshipMethod ; $ entity = $ this -> parentEntity ; $ entityMap = Manager :: getMapper ( $ entity ) -> getEntityMap ( ) ; return $ entityMap -> $ relation ( $ entity ) ; } | Return instance of the underlying relationship . |
211 | protected function getTypeStringForEntity ( $ class , EntityMap $ entityMap ) { $ class = $ entityMap -> getClass ( ) ; $ type = array_keys ( $ entityMap -> getDiscriminatorColumnMap ( ) , $ class ) ; if ( count ( $ type ) == 0 ) { return $ class ; } return $ type [ 0 ] ; } | Get the normalized value to use for query on discriminator column . |
212 | public function remove ( Query $ query ) { $ query = $ query -> getQuery ( ) ; foreach ( ( array ) $ query -> wheres as $ key => $ where ) { if ( $ this -> isSingleTableConstraint ( $ where , $ this -> column ) ) { unset ( $ query -> wheres [ $ key ] ) ; $ query -> wheres = array_values ( $ query -> wheres ) ; } } } | Remove the scope from the given Analogue query builder . |
213 | protected function getKeys ( array $ entities , $ key = null ) { if ( is_null ( $ key ) ) { $ key = $ this -> relatedMap -> getKeyName ( ) ; } $ host = $ this ; return array_unique ( array_values ( array_map ( function ( $ value ) use ( $ key , $ host ) { if ( ! $ value instanceof InternallyMappable ) { $ value = $ host -> factory -> make ( $ value ) ; } return $ value -> getEntityAttribute ( $ key ) ; } , $ entities ) ) ) ; } | Get all of the primary keys for an array of entities . |
214 | protected function getKeysFromResults ( array $ results , $ key = null ) { if ( is_null ( $ key ) ) { $ key = $ this -> parentMap -> getKeyName ( ) ; } return array_unique ( array_values ( array_map ( function ( $ value ) use ( $ key ) { return $ value [ $ key ] ; } , $ results ) ) ) ; } | Get all the keys from a result set . |
215 | protected function cacheRelation ( $ results , $ relation ) { $ cache = $ this -> parentMapper -> getEntityCache ( ) ; $ cache -> cacheLoadedRelationResult ( $ this -> parent -> getEntityKeyName ( ) , $ relation , $ results , $ this ) ; } | Cache the link between parent and related into the mapper s Entity Cache . |
216 | protected function getEntityHash ( Mappable $ entity ) { $ class = get_class ( $ entity ) ; $ keyName = Mapper :: getMapper ( $ class ) -> getEntityMap ( ) -> getKeyName ( ) ; return $ class . '.' . $ entity -> getEntityAttribute ( $ keyName ) ; } | Get a combo type . primaryKey . |
217 | public function build ( array $ attributes ) { if ( ! $ this -> useCache || $ this -> entityMap -> getKeyName ( ) === null ) { return $ this -> buildEntity ( $ attributes ) ; } $ instanceCache = $ this -> mapper -> getInstanceCache ( ) ; $ id = $ this -> getPrimaryKeyValue ( $ attributes ) ; return $ instanceCache -> has ( $ id ) ? $ instanceCache -> get ( $ id ) : $ this -> buildEntity ( $ attributes ) ; } | Convert an array of attributes into an entity or retrieve entity instance from cache . |
218 | protected function buildEntity ( array $ attributes ) { $ wrapper = $ this -> getWrapperInstance ( ) ; $ this -> hydrateValueObjects ( $ attributes ) ; $ wrapper -> setEntityAttributes ( $ attributes ) ; $ wrapper -> setProxies ( ) ; $ entity = $ wrapper -> unwrap ( ) ; if ( $ this -> entityMap -> getKeyName ( ) !== null ) { $ id = $ this -> getPrimaryKeyValue ( $ attributes ) ; $ this -> mapper -> getInstanceCache ( ) -> add ( $ entity , $ id ) ; } return $ entity ; } | Actually build an entity . |
219 | protected function hydrateValueObjects ( & $ attributes ) { foreach ( $ this -> entityMap -> getEmbeddables ( ) as $ localKey => $ valueClass ) { $ this -> hydrateValueObject ( $ attributes , $ localKey , $ valueClass ) ; } } | Hydrate value object embedded in this entity . |
220 | protected function hydrateValueObject ( & $ attributes , $ localKey , $ valueClass ) { $ map = $ this -> mapper -> getManager ( ) -> getValueMap ( $ valueClass ) ; $ embeddedAttributes = $ map -> getAttributes ( ) ; $ valueObject = $ this -> mapper -> getManager ( ) -> getValueObjectInstance ( $ valueClass ) ; $ voWrapper = $ this -> factory -> make ( $ valueObject ) ; foreach ( $ embeddedAttributes as $ key ) { $ prefix = snake_case ( class_basename ( $ valueClass ) ) . '_' ; $ voWrapper -> setEntityAttribute ( $ key , $ attributes [ $ prefix . $ key ] ) ; unset ( $ attributes [ $ prefix . $ key ] ) ; } $ attributes [ $ localKey ] = $ voWrapper -> getObject ( ) ; } | Hydrate a single value object . |
221 | public function mapper ( $ entity , $ entityMap = null ) { if ( $ entity instanceof Wrapper ) { throw new MappingException ( 'Tried to instantiate mapper on wrapped Entity' ) ; } $ entity = $ this -> resolveEntityClass ( $ entity ) ; $ entity = $ this -> getInverseMorphMap ( $ entity ) ; if ( array_key_exists ( $ entity , $ this -> mappers ) ) { return $ this -> mappers [ $ entity ] ; } else { return $ this -> buildMapper ( $ entity , $ entityMap ) ; } } | Create a mapper for a given entity . |
222 | protected function resolveEntityClass ( $ entity ) { if ( $ this -> isTraversable ( $ entity ) ) { if ( ! count ( $ entity ) ) { throw new \ InvalidArgumentException ( 'Length of Entity collection must be greater than 0' ) ; } $ firstEntityItem = ( $ entity instanceof \ Iterator ) ? $ entity -> current ( ) : current ( $ entity ) ; return $ this -> resolveEntityClass ( $ firstEntityItem ) ; } if ( is_object ( $ entity ) ) { return get_class ( $ entity ) ; } if ( is_string ( $ entity ) ) { return $ entity ; } throw new \ InvalidArgumentException ( 'Invalid entity type' ) ; } | This method resolve entity class from mappable instances or iterators . |
223 | protected function buildMapper ( $ entity , $ entityMap ) { if ( ! $ this -> isRegisteredEntity ( $ entity ) ) { $ this -> register ( $ entity , $ entityMap ) ; } $ entityMap = $ this -> entityClasses [ $ entity ] ; $ factory = new MapperFactory ( $ this -> drivers , $ this -> eventDispatcher , $ this ) ; $ mapper = $ factory -> make ( $ entity , $ entityMap ) ; $ this -> mappers [ $ entity ] = $ mapper ; if ( ! $ entityMap -> isBooted ( ) ) { $ entityMap -> boot ( ) ; } if ( $ this -> cache !== null && ! $ this -> cache -> has ( $ entityMap -> getClass ( ) ) && ! $ this -> isAnonymous ( $ entityMap ) ) { $ this -> cache -> set ( $ entityMap -> getClass ( ) , serialize ( $ entityMap ) , 1440 ) ; } return $ mapper ; } | Build a new Mapper instance for a given Entity . |
224 | public function isRegisteredEntity ( $ entity ) { if ( ! is_string ( $ entity ) ) { $ entity = get_class ( $ entity ) ; } return array_key_exists ( $ entity , $ this -> entityClasses ) ; } | Check if the entity is already registered . |
225 | public function isRegisteredValueObject ( $ object ) { if ( ! is_string ( $ object ) ) { $ object = get_class ( $ object ) ; } return array_key_exists ( $ object , $ this -> valueClasses ) ; } | Check if a value class is already registered . |
226 | public function register ( $ entity , $ entityMap = null ) { if ( ! is_string ( $ entity ) ) { $ entity = get_class ( $ entity ) ; } if ( $ this -> isRegisteredEntity ( $ entity ) ) { throw new MappingException ( "Entity $entity is already registered." ) ; } if ( ! class_exists ( $ entity ) ) { throw new MappingException ( "Class $entity does not exists" ) ; } if ( $ entityMap === null ) { $ entityMap = $ this -> getEntityMapInstanceFor ( $ entity ) ; } if ( is_string ( $ entityMap ) ) { $ entityMap = new $ entityMap ( ) ; } if ( ! $ entityMap instanceof EntityMap ) { throw new MappingException ( get_class ( $ entityMap ) . ' must be an instance of EntityMap.' ) ; } $ entityMap -> setClass ( $ entity ) ; $ this -> entityClasses [ $ entity ] = $ entityMap ; } | Register an entity . |
227 | protected function getEntityMapInstanceFor ( $ entity ) { $ entityMap = $ this -> getEntityMapInstanceFromCache ( $ entity ) ; if ( $ entityMap !== null ) { return $ entityMap ; } if ( class_exists ( $ entity . 'Map' ) ) { $ map = $ entity . 'Map' ; $ map = new $ map ( ) ; return $ map ; } if ( $ map = $ this -> getMapFromNamespaces ( $ entity ) ) { return $ map ; } if ( $ this -> strictMode ) { throw new EntityMapNotFoundException ( "No Map registered for $entity" ) ; } $ map = $ this -> getNewEntityMap ( ) ; return $ map ; } | Get the entity map instance for a custom entity . |
228 | protected function getEntityMapInstanceFromCache ( string $ entityClass ) { if ( $ this -> cache == null ) { return ; } if ( $ this -> cache -> has ( $ entityClass ) ) { return unserialize ( $ this -> cache -> get ( $ entityClass ) ) ; } } | Get Entity Map instance from cache . |
229 | public function repository ( $ entity ) { if ( ! is_string ( $ entity ) ) { $ entity = get_class ( $ entity ) ; } if ( array_key_exists ( $ entity , $ this -> repositories ) ) { return $ this -> repositories [ $ entity ] ; } $ this -> repositories [ $ entity ] = new Repository ( $ this -> mapper ( $ entity ) ) ; return $ this -> repositories [ $ entity ] ; } | Get the Repository instance for the given Entity . |
230 | public function isValueObject ( $ object ) { if ( ! is_string ( $ object ) ) { $ object = get_class ( $ object ) ; } return array_key_exists ( $ object , $ this -> valueClasses ) ; } | Return true is the object is registered as value object . |
231 | public function getValueMap ( $ valueObject ) { if ( ! is_string ( $ valueObject ) ) { $ valueObject = get_class ( $ valueObject ) ; } if ( ! array_key_exists ( $ valueObject , $ this -> valueClasses ) ) { $ this -> registerValueObject ( $ valueObject ) ; } $ valueMap = new $ this -> valueClasses [ $ valueObject ] ( ) ; $ valueMap -> setClass ( $ valueObject ) ; return $ valueMap ; } | Get the Value Map for a given Value Object Class . |
232 | public function registerValueObject ( $ valueObject , $ valueMap = null ) { if ( ! is_string ( $ valueObject ) ) { $ valueObject = get_class ( $ valueObject ) ; } if ( $ valueMap === null ) { if ( ! $ valueMap = $ this -> getMapFromNamespaces ( $ valueObject ) ) { $ valueMap = $ valueObject . 'Map' ; } else { $ valueMap = get_class ( $ valueMap ) ; } } if ( ! class_exists ( $ valueMap ) ) { throw new MappingException ( "$valueMap doesn't exists" ) ; } $ this -> valueClasses [ $ valueObject ] = $ valueMap ; } | Register a Value Object . |
233 | public function registerPlugin ( $ plugin ) { $ plugin = new $ plugin ( $ this ) ; $ this -> events = array_merge ( $ this -> events , $ plugin -> getCustomEvents ( ) ) ; $ plugin -> register ( ) ; } | Register Analogue Plugin . |
234 | public function registerGlobalEvent ( $ event , $ callback ) { if ( ! array_key_exists ( $ event , $ this -> events ) ) { throw new \ LogicException ( "Analogue : Event $event doesn't exist" ) ; } $ this -> eventDispatcher -> listen ( "analogue.{$event}.*" , $ callback ) ; } | Register event listeners that will be fired regardless the type of the entity . |
235 | public function make ( $ entityClass , EntityMap $ entityMap ) { $ driver = $ entityMap -> getDriver ( ) ; $ connection = $ entityMap -> getConnection ( ) ; $ adapter = $ this -> drivers -> getAdapter ( $ driver , $ connection ) ; $ entityMap -> setDateFormat ( $ adapter -> getDateFormat ( ) ) ; $ mapper = new Mapper ( $ entityMap , $ adapter , $ this -> dispatcher , $ this -> manager ) ; $ mapper -> fireEvent ( 'initializing' , $ mapper ) ; if ( ! $ entityMap -> isBooted ( ) ) { $ entityMap -> initialize ( ) ; } if ( $ entityMap -> getInheritanceType ( ) == 'single_table' ) { $ scope = new SingleTableInheritanceScope ( $ entityMap ) ; $ mapper -> addGlobalScope ( $ scope ) ; } $ mapper -> fireEvent ( 'initialized' , $ mapper ) ; return $ mapper ; } | Return a new Mapper instance . |
236 | protected function buildDictionary ( $ results ) { foreach ( $ results as $ result ) { if ( $ result [ $ this -> morphType ] ) { $ this -> dictionary [ $ result [ $ this -> morphType ] ] [ $ result [ $ this -> foreignKey ] ] [ ] = $ result ; } } } | Build a dictionary with the entities . |
237 | public function getForeignKeyValuePair ( $ related ) { $ foreignKey = $ this -> getForeignKey ( ) ; if ( $ related ) { $ wrapper = $ this -> factory -> make ( $ related ) ; $ relatedKey = $ this -> relatedMap -> getKeyName ( ) ; return [ $ foreignKey => $ wrapper -> getEntityAttribute ( $ relatedKey ) , $ this -> morphType => $ wrapper -> getMap ( ) -> getMorphClass ( ) , ] ; } else { return [ $ foreignKey => null ] ; } } | Get the foreign key value pair for a related object . |
238 | public function find ( $ key , $ default = null ) { if ( $ key instanceof Mappable ) { $ key = $ this -> getEntityKey ( $ key ) ; } return array_first ( $ this -> items , function ( $ entity , $ itemKey ) use ( $ key ) { return $ this -> getEntityKey ( $ entity ) == $ key ; } , $ default ) ; } | Find an entity in the collection by key . |
239 | public function getEntityHashes ( ) { return array_map ( function ( $ entity ) { $ class = get_class ( $ entity ) ; $ mapper = Manager :: getMapper ( $ class ) ; $ keyName = $ mapper -> getEntityMap ( ) -> getKeyName ( ) ; return $ class . '.' . $ entity -> getEntityAttribute ( $ keyName ) ; } , $ this -> items ) ; } | Generic function for returning class . key value pairs . |
240 | public function getSubsetByHashes ( array $ hashes ) { $ subset = [ ] ; foreach ( $ this -> items as $ item ) { $ class = get_class ( $ item ) ; $ mapper = Manager :: getMapper ( $ class ) ; $ keyName = $ mapper -> getEntityMap ( ) -> getKeyName ( ) ; if ( in_array ( $ class . '.' . $ item -> $ keyName , $ hashes ) ) { $ subset [ ] = $ item ; } } return $ subset ; } | Get a subset of the collection from entity hashes . |
241 | public function diff ( $ items ) { $ diff = new static ( ) ; $ dictionary = $ this -> getDictionary ( $ items ) ; foreach ( $ this -> items as $ item ) { if ( ! isset ( $ dictionary [ $ this -> getEntityKey ( $ item ) ] ) ) { $ diff -> add ( $ item ) ; } } return $ diff ; } | Diff the collection with the given items . |
242 | public function expand ( array $ options = array ( ) , $ dynamic = false ) { $ this -> mux = $ mux = new Mux ( ) ; $ routes = ControllerRouteBuilder :: build ( $ this ) ; foreach ( $ routes as $ route ) { if ( $ dynamic ) { $ mux -> add ( $ route [ 0 ] , array ( $ this , $ route [ 1 ] ) , array_merge ( $ options , $ route [ 2 ] ) ) ; } else { $ mux -> add ( $ route [ 0 ] , array ( get_class ( $ this ) , $ route [ 1 ] ) , array_merge ( $ options , $ route [ 2 ] ) ) ; } } $ mux -> sort ( ) ; return $ mux ; } | Expand controller actions to Mux object . |
243 | public static function parseActionMethods ( $ con ) { $ refClass = new ReflectionClass ( $ con ) ; $ methodMap = [ ] ; $ parentClasses = [ ] ; $ parentClasses [ ] = $ parentClassRef = $ refClass ; while ( $ parent = $ parentClassRef -> getParentClass ( ) ) { $ parentClasses [ ] = $ parent ; $ parentClassRef = $ parent ; } foreach ( array_reverse ( $ parentClasses ) as $ class ) { foreach ( $ class -> getMethods ( ReflectionMethod :: IS_PUBLIC ) as $ method ) { if ( ! preg_match ( '/Action$/' , $ method -> getName ( ) ) ) { continue ; } if ( in_array ( $ method -> getName ( ) , [ 'runAction' , 'hasAction' ] ) ) { continue ; } $ meta = array ( 'class' => $ class -> getName ( ) ) ; $ annotations = self :: parseMethodAnnotation ( $ method ) ; if ( empty ( $ annotations ) ) { if ( isset ( $ methodMap [ $ method -> getName ( ) ] ) ) { $ annotations = $ methodMap [ $ method -> getName ( ) ] [ 0 ] ; } } $ methodMap [ $ method -> getName ( ) ] = array ( $ annotations , $ meta ) ; } } return $ methodMap ; } | parseActionMethods parses the route definition from annotation and return the method = > route meta data structure |
244 | protected static function translatePath ( $ methodName ) { $ methodName = preg_replace ( '/Action$/' , '' , $ methodName ) ; return '/' . preg_replace_callback ( '/[A-Z]/' , function ( $ matches ) { return '/' . strtolower ( $ matches [ 0 ] ) ; } , $ methodName ) ; } | Translate action method name into route path . |
245 | protected function getRequest ( $ recreate = false ) { if ( ! $ recreate && $ this -> _request ) { return $ this -> _request ; } return $ this -> _request = HttpRequest :: createFromGlobals ( $ this -> environment ) ; } | Create and Return HttpRequest object from the environment |
246 | public function runAction ( $ action , array $ vars = array ( ) ) { $ method = "{$action}Action" ; if ( ! method_exists ( $ this , $ method ) ) { throw new Exception ( "Controller method $method does not exist." ) ; } $ ro = new ReflectionObject ( $ this ) ; $ rm = $ ro -> getMethod ( $ method ) ; $ parameters = $ rm -> getParameters ( ) ; $ arguments = array ( ) ; foreach ( $ parameters as $ param ) { if ( isset ( $ vars [ $ param -> getName ( ) ] ) ) { $ arguments [ ] = $ vars [ $ param -> getName ( ) ] ; } } return call_user_func_array ( array ( $ this , $ method ) , $ arguments ) ; } | Run controller action |
247 | public function forward ( $ controller , $ actionName = 'index' , $ parameters = array ( ) ) { if ( is_string ( $ controller ) ) { $ controller = new $ controller ; } return $ controller -> runAction ( $ actionName , $ parameters ) ; } | Forward to another controller action |
248 | public function isOneOfHosts ( array $ hosts ) { foreach ( $ hosts as $ host ) { if ( $ this -> matchHost ( $ host ) ) { return true ; } } return false ; } | Check if the request host is in the list of host . |
249 | public static function create ( $ method , $ path , array $ env = array ( ) ) { $ request = new self ( $ method , $ path ) ; if ( function_exists ( 'getallheaders' ) ) { $ request -> headers = getallheaders ( ) ; } else { $ request -> headers = self :: createHeadersFromServerGlobal ( $ env ) ; } if ( isset ( $ env [ '_SERVER' ] ) ) { $ request -> serverParameters = $ env [ '_SERVER' ] ; } else { $ request -> serverParameters = $ env ; } $ request -> parameters = isset ( $ env [ '_REQUEST' ] ) ? $ env [ '_REQUEST' ] : array ( ) ; $ request -> queryParameters = isset ( $ env [ '_GET' ] ) ? $ env [ '_GET' ] : array ( ) ; $ request -> bodyParameters = isset ( $ env [ '_POST' ] ) ? $ env [ '_POST' ] : array ( ) ; $ request -> cookieParameters = isset ( $ env [ '_COOKIE' ] ) ? $ env [ '_COOKIE' ] : array ( ) ; $ request -> sessionParameters = isset ( $ env [ '_SESSION' ] ) ? $ env [ '_SESSION' ] : array ( ) ; return $ request ; } | A helper function for creating request object based on request method and request uri . |
250 | public static function createFromEnv ( array $ env ) { if ( isset ( $ env [ '__request_object' ] ) ) { return $ env [ '__request_object' ] ; } if ( isset ( $ env [ 'PATH_INFO' ] ) ) { $ path = $ env [ 'PATH_INFO' ] ; } elseif ( isset ( $ env [ 'REQUEST_URI' ] ) ) { $ path = $ env [ 'REQUEST_URI' ] ; } elseif ( isset ( $ env [ '_SERVER' ] [ 'PATH_INFO' ] ) ) { $ path = $ env [ '_SERVER' ] [ 'PATH_INFO' ] ; } elseif ( isset ( $ env [ '_SERVER' ] [ 'REQUEST_URI' ] ) ) { $ path = $ env [ '_SERVER' ] [ 'REQUEST_URI' ] ; } else { $ path = '/' ; } $ requestMethod = 'GET' ; if ( isset ( $ env [ 'REQUEST_METHOD' ] ) ) { $ requestMethod = $ env [ 'REQUEST_METHOD' ] ; } else if ( isset ( $ env [ '_SERVER' ] [ 'REQUEST_METHOD' ] ) ) { $ requestMethod = $ env [ '_SERVER' ] [ 'REQUEST_METHOD' ] ; } $ request = new self ( $ requestMethod , $ path ) ; if ( function_exists ( 'getallheaders' ) ) { $ request -> headers = getallheaders ( ) ; } else { $ request -> headers = self :: createHeadersFromServerGlobal ( $ env ) ; } if ( isset ( $ env [ '_SERVER' ] ) ) { $ request -> serverParameters = $ env [ '_SERVER' ] ; } else { $ request -> serverParameters = $ env ; } $ request -> parameters = $ env [ '_REQUEST' ] ; $ request -> queryParameters = $ env [ '_GET' ] ; $ request -> bodyParameters = $ env [ '_POST' ] ; $ request -> cookieParameters = $ env [ '_COOKIE' ] ; $ request -> sessionParameters = $ env [ '_SESSION' ] ; return $ env [ '__request_object' ] = $ request ; } | Create request object from global variables . |
251 | public function mount ( $ pattern , $ mux , array $ options = array ( ) ) { $ options [ 'mount_path' ] = $ pattern ; if ( $ mux instanceof Expandable ) { $ mux = $ mux -> expand ( $ options ) ; } else if ( $ mux instanceof Closure ) { if ( $ ret = $ mux ( $ mux = new Mux ( ) ) ) { if ( $ ret instanceof Mux ) { $ mux = $ ret ; } else { throw new LogicException ( 'Invalid object returned from Closure.' ) ; } } } elseif ( ( ! is_object ( $ mux ) || ! ( $ mux instanceof self ) ) && is_callable ( $ mux ) ) { $ mux ( $ mux = new self ( ) ) ; } $ mux -> setParent ( $ this ) ; $ options [ 'mux' ] = $ mux ; if ( $ this -> expand ) { $ pcre = strpos ( $ pattern , ':' ) !== false ; foreach ( $ mux -> routes as $ route ) { if ( $ route [ 0 ] || $ pcre ) { $ newPattern = $ pattern . ( $ route [ 0 ] ? $ route [ 3 ] [ 'pattern' ] : $ route [ 1 ] ) ; $ routeArgs = PatternCompiler :: compile ( $ newPattern , array_replace_recursive ( $ options , $ route [ 3 ] ) ) ; $ this -> appendPCRERoute ( $ routeArgs , $ route [ 2 ] ) ; } else { $ this -> routes [ ] = array ( false , $ pattern . $ route [ 1 ] , $ route [ 2 ] , isset ( $ route [ 3 ] ) ? array_replace_recursive ( $ options , $ route [ 3 ] ) : $ options , ) ; } } } else { $ muxId = $ mux -> getId ( ) ; $ this -> add ( $ pattern , $ muxId , $ options ) ; $ this -> submux [ $ muxId ] = $ mux ; } } | Mount a Mux or a Controller object on a specific path . |
252 | public function match ( $ path , RouteRequest $ request = null ) { $ requestMethod = null ; if ( $ request ) { $ requestMethod = self :: convertRequestMethodConstant ( $ request -> getRequestMethod ( ) ) ; } else if ( isset ( $ _SERVER [ 'REQUEST_METHOD' ] ) ) { $ requestMethod = self :: convertRequestMethodConstant ( $ _SERVER [ 'REQUEST_METHOD' ] ) ; } foreach ( $ this -> routes as $ route ) { if ( $ route [ 0 ] ) { if ( ! preg_match ( $ route [ 1 ] , $ path , $ matches ) ) { continue ; } $ route [ 3 ] [ 'vars' ] = $ matches ; if ( isset ( $ route [ 3 ] [ 'method' ] ) && $ route [ 3 ] [ 'method' ] != $ requestMethod ) { continue ; } if ( isset ( $ route [ 3 ] [ 'domain' ] ) && $ route [ 3 ] [ 'domain' ] != $ _SERVER [ 'HTTP_HOST' ] ) { continue ; } if ( isset ( $ route [ 3 ] [ 'secure' ] ) && $ route [ 3 ] [ 'secure' ] && $ _SERVER [ 'HTTPS' ] ) { continue ; } return $ route ; } else { if ( ( ( is_int ( $ route [ 2 ] ) || $ route [ 2 ] instanceof self || $ route [ 2 ] instanceof \ PHPSGI \ App ) && strncmp ( $ route [ 1 ] , $ path , strlen ( $ route [ 1 ] ) ) === 0 ) || $ route [ 1 ] == $ path ) { if ( isset ( $ route [ 3 ] [ 'method' ] ) && $ route [ 3 ] [ 'method' ] != $ requestMethod ) { continue ; } if ( isset ( $ route [ 3 ] [ 'domain' ] ) && $ route [ 3 ] [ 'domain' ] != $ _SERVER [ 'HTTP_HOST' ] ) { continue ; } if ( isset ( $ route [ 3 ] [ 'secure' ] ) && $ route [ 3 ] [ 'secure' ] && $ _SERVER [ 'HTTPS' ] ) { continue ; } return $ route ; } continue ; } } } | Find a matched route with the path constraint in the current mux object . |
253 | public function dispatch ( $ path , RouteRequest $ request = null ) { if ( $ route = $ this -> match ( $ path ) ) { if ( is_integer ( $ route [ 2 ] ) ) { $ submux = $ this -> submux [ $ route [ 2 ] ] ; $ options = $ route [ 3 ] ; if ( $ route [ 0 ] ) { $ matchedString = $ route [ 3 ] [ 'vars' ] [ 0 ] ; return $ submux -> dispatch ( substr ( $ path , strlen ( $ matchedString ) ) ) ; } else { $ s = substr ( $ path , strlen ( $ route [ 1 ] ) ) ; return $ submux -> dispatch ( substr ( $ path , strlen ( $ route [ 1 ] ) ) ? : '' ) ; } } return $ route ; } } | Match route in the current Mux and submuxes recursively . |
254 | public function url ( $ id , array $ params = array ( ) ) { $ route = $ this -> getRoute ( $ id ) ; if ( ! isset ( $ route ) ) { throw new \ RuntimeException ( 'Named route not found for id: ' . $ id ) ; } $ search = array ( ) ; foreach ( $ params as $ key => $ value ) { $ search [ ] = '#:' . preg_quote ( $ key , '#' ) . '\+?(?!\w)#' ; } $ pattern = preg_replace ( $ search , $ params , $ route [ 3 ] [ 'pattern' ] ) ; return preg_replace ( '#\(/?:.+\)|\(|\)|\\\\#' , '' , $ pattern ) ; } | url method generates the related URL for a route . |
255 | static function compile ( $ pattern , array $ options = array ( ) ) { $ route = self :: compilePattern ( $ pattern , $ options ) ; $ route [ 'compiled' ] = sprintf ( "#^%s$#xs" , $ route [ 'regex' ] ) ; $ route [ 'pattern' ] = $ pattern ; return $ route ; } | Compiles the current route instance . |
256 | public function validateRouteCallback ( array $ routes ) { foreach ( $ routes as $ route ) { $ callback = $ route [ 2 ] ; if ( is_array ( $ callback ) ) { $ class = $ callback [ 0 ] ; $ method = $ callback [ 1 ] ; if ( ! class_exists ( $ class , true ) ) { throw new Exception ( "Controller {$class} does not exist." ) ; } $ controller = new $ class ( ) ; if ( ! method_exists ( $ controller , $ method ) ) { throw new Exception ( "Method $method not found in controller $class." ) ; } } } } | validate controller classes and controller methods before compiling to route cache . |
257 | public function compile ( $ outFile ) { usort ( $ this -> mux -> routes , array ( 'Pux\\MuxCompiler' , 'sort_routes' ) ) ; $ code = $ this -> mux -> export ( ) ; return file_put_contents ( $ outFile , '<?php return ' . $ code . '; /* version */' ) ; } | Compile merged routes to file . |
258 | public function expand ( array $ options = array ( ) , $ dynamic = false ) { $ mux = new Mux ( ) ; $ target = $ dynamic ? $ this : $ this -> getClass ( ) ; $ mux -> add ( '/:id' , [ $ target , 'updateAction' ] , array_merge ( $ options , array ( 'method' => REQUEST_METHOD_POST ) ) ) ; $ mux -> add ( '/:id' , [ $ target , 'loadAction' ] , array_merge ( $ options , array ( 'method' => REQUEST_METHOD_GET ) ) ) ; $ mux -> add ( '/:id' , [ $ target , 'deleteAction' ] , array_merge ( $ options , array ( 'method' => REQUEST_METHOD_DELETE ) ) ) ; $ mux -> add ( '' , [ $ target , 'createAction' ] , array_merge ( $ options , array ( 'method' => REQUEST_METHOD_POST ) ) ) ; $ mux -> add ( '' , [ $ target , 'collectionAction' ] , array_merge ( $ options , array ( 'method' => REQUEST_METHOD_GET ) ) ) ; return $ mux ; } | Expand controller actions into Mux object |
259 | public function addResource ( $ resourceId , Expandable $ controller ) { $ this -> resources [ $ resourceId ] = $ controller ; $ prefix = $ this -> options [ 'prefix' ] ; $ resourceMux = $ controller -> expand ( ) ; $ path = $ prefix . '/' . $ resourceId ; $ this -> mux -> mount ( $ path , $ resourceMux ) ; } | Register a RESTful resource into the Mux object . |
260 | public function build ( ) { $ prefix = $ this -> options [ 'prefix' ] ; foreach ( $ this -> resources as $ resId => $ controller ) { $ resourceMux = $ controller -> expand ( ) ; $ path = $ prefix . '/' . $ resId ; $ this -> mux -> mount ( $ path , $ resourceMux ) ; } return $ this -> mux ; } | build method returns a Mux object with registered resources . |
261 | public static function callback ( $ handler ) { if ( $ handler instanceof Closure ) { return $ handler ; } if ( is_object ( $ handler [ 0 ] ) ) { return $ handler ; } if ( is_string ( $ handler [ 0 ] ) ) { $ constructArgs = [ ] ; $ rc = new ReflectionClass ( $ handler [ 0 ] ) ; if ( isset ( $ options [ 'constructor_args' ] ) ) { $ con = $ handler [ 0 ] = $ rc -> newInstanceArgs ( $ constructArgs ) ; } else { $ con = $ handler [ 0 ] = $ rc -> newInstance ( ) ; } return $ handler ; } throw new LogicException ( 'Unsupported handler type' ) ; } | When creating the controller instance we don t care about the environment . |
262 | public static function execute ( array $ route , array $ environment = array ( ) , array $ response = array ( ) ) { list ( $ pcre , $ pattern , $ callbackArg , $ options ) = $ route ; $ callback = self :: callback ( $ callbackArg ) ; $ environment [ 'pux.route' ] = $ route ; if ( is_array ( $ callback ) && $ callback [ 0 ] instanceof Controller ) { $ environment [ 'pux.controller' ] = $ callback [ 0 ] ; $ environment [ 'pux.controller_action' ] = $ callback [ 1 ] ; } if ( $ callback instanceof Closure ) { $ return = $ callback ( $ environment , $ response ) ; } else if ( $ callback [ 0 ] instanceof \ PHPSGI \ App ) { $ return = $ callback [ 0 ] -> call ( $ environment , $ response ) ; } else if ( is_callable ( $ callback ) ) { $ return = call_user_func ( $ callback , $ environment , $ response ) ; } else { throw new \ LogicException ( "Invalid callback type." ) ; } if ( is_string ( $ return ) ) { if ( ! isset ( $ response [ 0 ] ) ) { $ response [ 0 ] = 200 ; } if ( ! isset ( $ response [ 1 ] ) ) { $ response [ 1 ] = [ ] ; } if ( ! isset ( $ response [ 2 ] ) ) { $ response [ 2 ] = $ return ; } return $ response ; } return $ return ; } | Execute the matched route . |
263 | protected function doExpandArrayProperties ( $ data , $ array , $ parent_keys = '' , $ reference_data = null ) { foreach ( $ array as $ key => $ value ) { if ( is_null ( $ value ) || is_bool ( $ value ) ) { continue ; } if ( is_array ( $ value ) ) { $ this -> doExpandArrayProperties ( $ data , $ value , $ parent_keys . "$key." , $ reference_data ) ; } else { $ this -> expandStringProperties ( $ data , $ parent_keys , $ reference_data , $ value , $ key ) ; } } } | Performs the actual property expansion . |
264 | protected function expandStringProperties ( $ data , $ parent_keys , $ reference_data , $ value , $ key ) { while ( strpos ( $ value , '${' ) !== false ) { $ original_value = $ value ; $ value = preg_replace_callback ( '/\$\{([^\$}]+)\}/' , function ( $ matches ) use ( $ data , $ reference_data ) { return $ this -> expandStringPropertiesCallback ( $ matches , $ data , $ reference_data ) ; } , $ value ) ; if ( $ original_value == $ value ) { break ; } if ( $ parent_keys ) { $ full_key = $ parent_keys . "$key" ; } else { $ full_key = $ key ; } $ data -> set ( $ full_key , $ value ) ; } return $ value ; } | Expand a single property . |
265 | public function package ( PassInterface $ pass , $ passName = '' ) { if ( $ pass -> getSerialNumber ( ) == '' ) { throw new \ InvalidArgumentException ( 'Pass must have a serial number to be packaged' ) ; } $ this -> populateRequiredInformation ( $ pass ) ; if ( $ this -> passValidator ) { if ( ! $ this -> passValidator -> validate ( $ pass ) ) { throw new PassInvalidException ( 'Failed to validate passbook' , $ this -> passValidator -> getErrors ( ) ) ; } ; } $ passDir = $ this -> preparePassDirectory ( $ pass ) ; file_put_contents ( $ passDir . 'pass.json' , self :: serialize ( $ pass ) ) ; $ this -> prepareImages ( $ pass , $ passDir ) ; $ this -> prepareLocalizations ( $ pass , $ passDir ) ; $ manifestJSONFile = $ this -> prepareManifest ( $ passDir ) ; $ this -> sign ( $ passDir , $ manifestJSONFile ) ; $ zipFile = $ this -> getNormalizedOutputPath ( ) . $ this -> getPassName ( $ passName , $ pass ) . self :: PASS_EXTENSION ; $ this -> zip ( $ passDir , $ zipFile ) ; $ this -> rrmdir ( $ passDir ) ; return new SplFileObject ( $ zipFile ) ; } | Creates a pkpass file |
266 | public function printDump ( $ maxItemsPerCollection = null , $ maxDepth = null ) { return printDump ( $ this -> getItems ( ) , $ maxItemsPerCollection , $ maxDepth ) ; } | Calls dump on this collection and then prints it using the var_export . |
267 | public function schedule ( Container $ laravel , Kernel $ kernel , Schedule $ schedule ) { $ events = $ schedule -> dueEvents ( $ laravel ) ; $ eventsRan = 0 ; $ messages = [ ] ; foreach ( $ events as $ event ) { if ( method_exists ( $ event , 'filtersPass' ) && ( new \ ReflectionMethod ( $ event , 'filtersPass' ) ) -> isPublic ( ) && ! $ event -> filtersPass ( $ laravel ) ) { continue ; } $ messages [ ] = 'Running: ' . $ event -> getSummaryForDisplay ( ) ; $ event -> run ( $ laravel ) ; ++ $ eventsRan ; } if ( count ( $ events ) === 0 || $ eventsRan === 0 ) { $ messages [ ] = 'No scheduled commands are ready to run.' ; } return $ this -> response ( $ messages ) ; } | This method is nearly identical to ScheduleRunCommand shipped with Laravel but since we are not interested in console output we couldn t reuse it |
268 | public function gf ( ) : self { $ arguments = func_get_args ( ) ; if ( func_num_args ( ) === 1 && ( $ image = $ arguments [ 0 ] ) instanceof ImageContract ) { $ bytesPerRow = $ image -> width ( ) ; $ byteCount = $ fieldCount = $ bytesPerRow * $ image -> height ( ) ; return $ this -> command ( 'GF' , 'A' , $ byteCount , $ fieldCount , $ bytesPerRow , $ image -> toAscii ( ) ) ; } array_unshift ( $ arguments , 'GF' ) ; return call_user_func_array ( [ $ this , 'command' ] , $ arguments ) ; } | Add GF command . |
269 | public function toZpl ( bool $ newlines = false ) : string { return implode ( $ newlines ? "\n" : '' , array_merge ( [ '^XA' ] , $ this -> zpl , [ '^XZ' ] ) ) ; } | Convert instance to ZPL . |
270 | protected function connect ( string $ host , int $ port ) : void { $ this -> socket = @ socket_create ( AF_INET , SOCK_STREAM , SOL_TCP ) ; if ( ! $ this -> socket || ! @ socket_connect ( $ this -> socket , $ host , $ port ) ) { $ error = $ this -> getLastError ( ) ; throw new CommunicationException ( $ error [ 'message' ] , $ error [ 'code' ] ) ; } } | Connect to printer . |
271 | public function send ( string $ zpl ) : void { if ( false === @ socket_write ( $ this -> socket , $ zpl ) ) { $ error = $ this -> getLastError ( ) ; throw new CommunicationException ( $ error [ 'message' ] , $ error [ 'code' ] ) ; } } | Send ZPL data to printer . |
272 | protected function encode ( ) : string { $ bitmap = null ; $ lastRow = null ; for ( $ y = 0 ; $ y < $ this -> height ; $ y ++ ) { $ bits = null ; for ( $ x = 0 ; $ x < $ this -> width ; $ x ++ ) { $ bits .= $ this -> decoder -> getBitAt ( $ x , $ y ) ; } $ bytes = str_split ( $ bits , 8 ) ; $ bytes [ ] = str_pad ( array_pop ( $ bytes ) , 8 , '0' ) ; $ row = null ; foreach ( $ bytes as $ byte ) { $ row .= sprintf ( '%02X' , bindec ( $ byte ) ) ; } $ bitmap .= $ this -> compress ( $ row , $ lastRow ) ; $ lastRow = $ row ; } return $ bitmap ; } | Encode the image in ASCII hexadecimal by looping over every pixel . |
273 | protected function compress ( string $ row , ? string $ lastRow ) : string { if ( $ row === $ lastRow ) { return ':' ; } $ row = $ this -> compressTrailingZerosOrOnes ( $ row ) ; $ row = $ this -> compressRepeatingCharacters ( $ row ) ; return $ row ; } | Compress a row of ASCII hexadecimal data . |
274 | protected function compressRepeatingCharacters ( string $ row ) : string { $ callback = function ( $ matches ) { $ original = $ matches [ 0 ] ; $ repeat = strlen ( $ original ) ; $ count = null ; if ( $ repeat > 400 ) { $ count .= str_repeat ( 'z' , floor ( $ repeat / 400 ) ) ; $ repeat %= 400 ; } if ( $ repeat > 19 ) { $ count .= chr ( ord ( 'f' ) + floor ( $ repeat / 20 ) ) ; $ repeat %= 20 ; } if ( $ repeat > 0 ) { $ count .= chr ( ord ( 'F' ) + $ repeat ) ; } return $ count . substr ( $ original , 1 , 1 ) ; } ; return preg_replace_callback ( '/(.)(\1{2,})/' , $ callback , $ row ) ; } | Compress characters which repeat . |
275 | public static function fromString ( string $ data ) : self { if ( false === $ image = imagecreatefromstring ( $ data ) ) { throw new InvalidArgumentException ( 'Could not read image' ) ; } return new static ( $ image ) ; } | Create a new decoder instance from the specified string . |
276 | public function share ( $ key , $ value = null ) { if ( ! is_array ( $ key ) ) { return parent :: share ( $ key , $ this -> decorate ( $ value ) ) ; } return parent :: share ( $ this -> decorate ( $ key ) ) ; } | Add a piece of shared data to the factory . |
277 | public function offsetSet ( $ offset , $ value ) { if ( is_array ( $ this -> object ) ) { $ this -> object [ $ offset ] = $ value ; return ; } $ this -> object -> $ offset = $ value ; } | Set variable or key value using array access . |
278 | public function offsetUnset ( $ offset ) { if ( is_array ( $ this -> object ) ) { unset ( $ this -> object [ $ offset ] ) ; return ; } unset ( $ this -> object -> $ offset ) ; } | Unset a variable or key value using array access . |
279 | protected function getPresenterMethodFromVariable ( $ variable ) { $ method = 'present' . str_replace ( ' ' , '' , ucwords ( str_replace ( [ '-' , '_' ] , ' ' , $ variable ) ) ) ; if ( method_exists ( $ this , $ method ) ) { return $ method ; } } | Fetch the present method name for the given variable . |
280 | public function registerFactory ( ) { $ this -> app -> singleton ( 'view' , function ( $ app ) { $ resolver = $ app [ 'view.engine.resolver' ] ; $ finder = $ app [ 'view.finder' ] ; $ factory = new View \ Factory ( $ resolver , $ finder , $ app [ 'events' ] , $ app [ 'presenter.decorator' ] ) ; $ factory -> setContainer ( $ app ) ; $ factory -> share ( 'app' , $ app ) ; return $ factory ; } ) ; } | Copied from the view service provider ... |
281 | public static function bootSummable ( ) { static :: created ( function ( $ model ) { $ sumCache = new SumCache ( $ model ) ; $ sumCache -> apply ( function ( $ config ) use ( $ model , $ sumCache ) { $ sumCache -> updateCacheRecord ( $ config , '+' , $ model -> { $ config [ 'columnToSum' ] } , $ model -> { $ config [ 'foreignKey' ] } ) ; } ) ; } ) ; static :: updated ( function ( $ model ) { ( new SumCache ( $ model ) ) -> update ( ) ; } ) ; static :: deleted ( function ( $ model ) { $ sumCache = new SumCache ( $ model ) ; $ sumCache -> apply ( function ( $ config ) use ( $ model , $ sumCache ) { $ sumCache -> updateCacheRecord ( $ config , '-' , $ model -> { $ config [ 'columnToSum' ] } , $ model -> { $ config [ 'foreignKey' ] } ) ; } ) ; } ) ; } | Boot the trait and its event bindings when a model is created . |
282 | public static function fromId ( $ id ) { $ salt = md5 ( uniqid ( ) . $ id ) ; $ alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ; $ slug = with ( new Hashids ( $ salt , $ length = 8 , $ alphabet ) ) -> encode ( $ id ) ; return new Slug ( $ slug ) ; } | Generate a new 8 - character slug . |
283 | public function getTrueKey ( $ key ) { if ( $ this -> isCamelCase ( ) && strpos ( $ key , 'pivot_' ) === false ) { $ key = camel_case ( $ key ) ; } return $ key ; } | Retrieves the true key name for a key . |
284 | public function __isset ( $ key ) { return parent :: __isset ( $ key ) || parent :: __isset ( $ this -> getSnakeKey ( $ key ) ) ; } | Because we are changing the case of keys and want to use camelCase throughout the application whenever we do isset checks we need to ensure that we check using snake_case . |
285 | private function rebuild ( $ className ) { $ instance = new $ className ; if ( method_exists ( $ instance , 'countCaches' ) ) { $ this -> info ( "Rebuilding [$className] count caches" ) ; $ countCache = new CountCache ( $ instance ) ; $ countCache -> rebuild ( ) ; } if ( method_exists ( $ instance , 'sumCaches' ) ) { $ this -> info ( "Rebuilding [$className] sum caches" ) ; $ sumCache = new SumCache ( $ instance ) ; $ sumCache -> rebuild ( ) ; } } | Rebuilds the caches for the given class . |
286 | public static function bootSluggable ( ) { static :: creating ( function ( $ model ) { $ model -> generateSlug ( ) ; } ) ; static :: created ( function ( $ model ) { if ( $ model -> slugStrategy ( ) == 'id' ) { $ model -> generateIdSlug ( ) ; $ model -> save ( ) ; } } ) ; } | When added to a model the trait will bind to the creating and created events generating the appropriate slugs as necessary . |
287 | public function generateIdSlug ( ) { $ slug = Slug :: fromId ( $ this -> getKey ( ) ) ; $ attempts = 10 ; while ( $ this -> isExistingSlug ( $ slug ) ) { if ( $ attempts <= 0 ) { throw new UnableToCreateSlugException ( "Unable to find unique slug for record '{$this->getKey()}', tried 10 times..." ) ; } $ slug = Slug :: random ( ) ; $ attempts -- ; } $ this -> setSlugValue ( $ slug ) ; } | Generate a slug based on the main model key . |
288 | public function generateTitleSlug ( array $ fields ) { static $ attempts = 0 ; $ titleSlug = Slug :: fromTitle ( implode ( '-' , $ this -> getTitleFields ( $ fields ) ) ) ; if ( $ attempts > 0 ) { $ titleSlug . "-{$attempts}" ; } $ this -> setSlugValue ( $ titleSlug ) ; $ attempts ++ ; } | Generate a slug string based on the fields required . |
289 | public function generateSlug ( ) { $ strategy = $ this -> slugStrategy ( ) ; if ( $ strategy == 'uuid' ) { $ this -> generateIdSlug ( ) ; } elseif ( $ strategy != 'id' ) { $ this -> generateTitleSlug ( ( array ) $ strategy ) ; } } | Generate the slug for the model based on the model s slug strategy . |
290 | public function rebuildCacheRecord ( array $ config , Model $ model , $ command , $ aggregateField = null ) { $ config = $ this -> processConfig ( $ config ) ; $ table = $ this -> getModelTable ( $ model ) ; if ( is_null ( $ aggregateField ) ) { $ aggregateField = $ config [ 'foreignKey' ] ; } else { $ aggregateField = snake_case ( $ aggregateField ) ; } $ sql = DB :: table ( $ table ) -> select ( $ config [ 'foreignKey' ] ) -> groupBy ( $ config [ 'foreignKey' ] ) ; if ( strtolower ( $ command ) == 'count' ) { $ aggregate = $ sql -> count ( $ aggregateField ) ; } else if ( strtolower ( $ command ) == 'sum' ) { $ aggregate = $ sql -> sum ( $ aggregateField ) ; } else if ( strtolower ( $ command ) == 'avg' ) { $ aggregate = $ sql -> avg ( $ aggregateField ) ; } else { $ aggregate = null ; } return DB :: table ( $ config [ 'table' ] ) -> update ( [ $ config [ 'field' ] => $ aggregate ] ) ; } | Rebuilds the cache for the records in question . |
291 | protected function processConfig ( array $ config ) { return [ 'model' => $ config [ 'model' ] , 'table' => $ this -> getModelTable ( $ config [ 'model' ] ) , 'field' => snake_case ( $ config [ 'field' ] ) , 'key' => snake_case ( $ this -> key ( $ config [ 'key' ] ) ) , 'foreignKey' => snake_case ( $ this -> key ( $ config [ 'foreignKey' ] ) ) , ] ; } | Process configuration parameters to check key names fix snake casing etc .. |
292 | protected function key ( $ field ) { if ( method_exists ( $ this -> model , 'getTrueKey' ) ) { return $ this -> model -> getTrueKey ( $ field ) ; } return $ field ; } | Returns the true key for a given field . |
293 | protected function getModelTable ( $ model ) { if ( ! is_object ( $ model ) ) { $ model = new $ model ; } return DB :: getTablePrefix ( ) . $ model -> getTable ( ) ; } | Returns the table for a given model . Model can be an Eloquent model object or a full namespaced class string . |
294 | public function rebuild ( ) { $ this -> apply ( function ( $ config ) { $ this -> rebuildCacheRecord ( $ config , $ this -> model , 'SUM' , $ config [ 'columnToSum' ] ) ; } ) ; } | Rebuild the count caches from the database |
295 | public function update ( ) { $ this -> apply ( function ( $ config ) { $ foreignKey = snake_case ( $ this -> key ( $ config [ 'foreignKey' ] ) ) ; $ amount = $ this -> model -> { $ config [ 'columnToSum' ] } ; if ( $ this -> model -> getOriginal ( $ foreignKey ) && $ this -> model -> { $ foreignKey } != $ this -> model -> getOriginal ( $ foreignKey ) ) { $ this -> updateCacheRecord ( $ config , '-' , $ amount , $ this -> model -> getOriginal ( $ foreignKey ) ) ; $ this -> updateCacheRecord ( $ config , '+' , $ amount , $ this -> model -> { $ foreignKey } ) ; } } ) ; } | Update the cache for all operations . |
296 | protected function config ( $ cacheKey , $ cacheOptions ) { $ opts = [ ] ; if ( is_numeric ( $ cacheKey ) ) { if ( is_array ( $ cacheOptions ) ) { $ opts = $ cacheOptions ; $ relatedModel = array_get ( $ opts , 'model' ) ; } else { $ relatedModel = $ cacheOptions ; } } else { $ relatedModel = $ cacheOptions ; $ opts [ 'field' ] = $ cacheKey ; if ( is_array ( $ cacheOptions ) ) { if ( isset ( $ cacheOptions [ 3 ] ) ) { $ opts [ 'key' ] = $ cacheOptions [ 3 ] ; } if ( isset ( $ cacheOptions [ 2 ] ) ) { $ opts [ 'foreignKey' ] = $ cacheOptions [ 2 ] ; } if ( isset ( $ cacheOptions [ 1 ] ) ) { $ opts [ 'columnToSum' ] = $ cacheOptions [ 1 ] ; } if ( isset ( $ cacheOptions [ 0 ] ) ) { $ relatedModel = $ cacheOptions [ 0 ] ; } } } return $ this -> defaults ( $ opts , $ relatedModel ) ; } | Takes a registered sum cache and setups up defaults . |
297 | protected function defaults ( $ options , $ relatedModel ) { $ defaults = [ 'model' => $ relatedModel , 'columnToSum' => 'total' , 'field' => $ this -> field ( $ this -> model , 'total' ) , 'foreignKey' => $ this -> field ( $ relatedModel , 'id' ) , 'key' => 'id' ] ; return array_merge ( $ defaults , $ options ) ; } | Returns necessary defaults overwritten by provided options . |
298 | private function update ( $ model , $ operation ) { $ countCache = new CountCache ( $ model ) ; $ countCache -> apply ( function ( $ config ) use ( $ countCache , $ model , $ operation ) { $ countCache -> updateCacheRecord ( $ config , $ operation , 1 , $ model -> { $ config [ 'foreignKey' ] } ) ; } ) ; } | Handle most update operations of the count cache . |
299 | protected function prepareFromYaml ( array $ categories = [ ] ) : array { $ data = array ( ) ; foreach ( $ this -> paths as $ path ) { $ files = Finder :: create ( ) -> files ( ) -> in ( $ path ) -> name ( '*.yml' ) ; foreach ( $ files as $ file ) { $ fileData = Yaml :: parse ( $ file -> getContents ( ) ) ; $ category = $ fileData [ 'category' ] ; if ( count ( $ categories ) > 0 && ! in_array ( $ category , $ categories ) ) { continue ; } array_walk ( $ fileData [ 'questions' ] , function ( & $ item ) use ( $ category ) { $ item [ 'category' ] = $ category ; } ) ; $ data = array_merge ( $ data , $ fileData [ 'questions' ] ) ; } } return $ data ; } | Prepares data from Yaml files and returns an array of questions |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.