sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function staticMapUrl(array $options = []) { $mapUrl = $this->_protocol() . static::STATIC_API; /* $params = array( 'mobile' => 'false', 'format' => 'png', //'center' => false ); if (!empty($options['mobile'])) { $params['mobile'] = 'true'; } */ $defaults = $this->_config['staticMap'] + $this->_config; $mapOptions = $options + $defaults; $params = array_intersect_key($mapOptions, [ 'mobile' => null, 'format' => null, 'size' => null, //'zoom' => null, //'lat' => null, //'lng' => null, //'visible' => null, //'type' => null, ]); // add API key to parameters. if ($this->_runtimeConfig['key']) { $params['key'] = $this->_runtimeConfig['key']; } // do we want zoom to auto-correct itself? if (!isset($options['zoom']) && !empty($mapOptions['markers']) || !empty($mapOptions['paths']) || !empty($mapOptions['visible'])) { $options['zoom'] = 'auto'; } // a position on the map that is supposed to stay visible at all cost if (!empty($mapOptions['visible'])) { $params['visible'] = urlencode($mapOptions['visible']); } // center and zoom are not necessary if path, visible or markers are given if (!isset($options['center']) || $options['center'] === false) { // dont use it } elseif ($options['center'] === true && $mapOptions['lat'] !== null && $mapOptions['lng'] !== null) { $params['center'] = urlencode((string)$mapOptions['lat'] . ',' . (string)$mapOptions['lng']); } elseif (!empty($options['center'])) { $params['center'] = urlencode($options['center']); } /*else { // try to read from markers array??? if (isset($options['markers']) && count($options['markers']) == 1) { //pr ($options['markers']); } }*/ if (!isset($options['zoom']) || $options['zoom'] === false) { // dont use it } else { if ($options['zoom'] === 'auto') { if (!empty($options['markers']) && strpos($options['zoom'], '|') !== false) { // let google find the best zoom value itself } else { // do something here? } } else { $params['zoom'] = $options['zoom']; } } if (array_key_exists($mapOptions['type'], $this->types)) { $params['maptype'] = $this->types[$mapOptions['type']]; } else { $params['maptype'] = $mapOptions['type']; } $params['maptype'] = strtolower($params['maptype']); // old: {latitude},{longitude},{color}{alpha-character} // new: @see staticMarkers() if (!empty($options['markers'])) { $params['markers'] = $options['markers']; } if (!empty($options['paths'])) { $params['path'] = $options['paths']; } // valXval if (!empty($options['size'])) { $params['size'] = $options['size']; } $pieces = []; foreach ($params as $key => $value) { if (is_array($value)) { $value = implode('&' . $key . '=', $value); } elseif ($value === true) { $value = 'true'; } elseif ($value === false) { $value = 'false'; } elseif ($value === null) { continue; } $pieces[] = $key . '=' . $value; } $options += [ 'escape' => true, ]; $query = implode('&', $pieces); if ($options['escape']) { $query = h($query); } return $mapUrl . '?' . $query; }
Creates a URL to a plain image map. Options: - escape: defaults to true (Deprecated as of CakePHP 3.5.1 and now has to be always false) @param array $options - see staticMap() for details @return string urlOfImage: http://...
entailment
public function staticPaths(array $pos = []) { $defaults = [ 'color' => 'blue', 'weight' => 5 // pixel ]; // not a 2-level array? make it one if (!isset($pos[0])) { $pos = [$pos]; } $res = []; foreach ($pos as $p) { $options = $p + $defaults; $markers = $options['path']; unset($options['path']); // prepare color if (!empty($options['color'])) { $options['color'] = $this->_prepColor($options['color']); } $path = []; foreach ($options as $key => $value) { $path[] = $key . ':' . urlencode($value); } foreach ($markers as $key => $pos) { if (is_array($pos)) { // lat/lng? $pos = $pos['lat'] . ',' . $pos['lng']; } $path[] = $pos; } $res[] = implode('|', $path); } return $res; }
Prepare paths for staticMap @param array $pos PathElementArrays - elements: [required] (multiple array(lat=>x, lng=>y) or just a address strings) - color: red/blue/green (optional, default blue) - weight: numeric (optional, default: 5) @return array Array of paths: e.g: color:0x0000FF80|weight:5|37.40303,-122.08334|37.39471,-122.07201|37.40589,-122.06171{|...}
entailment
public function staticMarkers(array $pos = [], array $style = []) { $markers = []; $verbose = false; $defaults = [ 'shadow' => 'true', 'color' => 'blue', 'label' => '', 'address' => '', 'size' => '' ]; // not a 2-level array? make it one if (!isset($pos[0])) { $pos = [$pos]; } // new in staticV2: separate styles! right now just merged foreach ($pos as $p) { $p += $style + $defaults; // adress or lat/lng? if (!empty($p['lat']) && !empty($p['lng'])) { $p['address'] = $p['lat'] . ',' . $p['lng']; } $p['address'] = urlencode($p['address']); $values = []; // prepare color if (!empty($p['color'])) { $p['color'] = $this->_prepColor($p['color']); $values[] = 'color:' . $p['color']; } // label? A-Z0-9 if (!empty($p['label'])) { $values[] = 'label:' . strtoupper($p['label']); } if (!empty($p['size'])) { $values[] = 'size:' . $p['size']; } if (!empty($p['shadow'])) { $values[] = 'shadow:' . $p['shadow']; } if (!empty($p['icon'])) { $values[] = 'icon:' . urlencode($p['icon']); } $values[] = $p['address']; //TODO: icons $markers[] = implode('|', $values); } //TODO: shortcut? only possible if no custom params! if ($verbose) { } // long: markers=styles1|address1&markers=styles2|address2&... // short: markers=styles,address1|address2|address3|... return $markers; }
Prepare markers for staticMap @param array $pos markerArrays - lat: xx.xxxxxx (necessary) - lng: xx.xxxxxx (necessary) - address: (instead of lat/lng) - color: red/blue/green (optional, default blue) - label: a-z or numbers (optional, default: s) - icon: custom icon (png, gif, jpg - max 64x64 - max 5 different icons per image) - shadow: TRUE/FALSE @param array $style (global) (overridden by custom marker styles) - color - label - icon - shadow @return array markers: color:green|label:Z|48,11|Berlin NEW: size:mid|color:red|label:E|37.400465,-122.073003|37.437328,-122.159928&markers=size:small|color:blue|37.369110,-122.096034 OLD: 40.702147,-74.015794,blueS|40.711614,-74.012318,greenG{|...}
entailment
protected function _protocol() { $https = $this->_runtimeConfig['https']; if ($https === null) { $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on'; } return $https ? 'https://' : '//'; }
Ensure that we stay on the appropriate protocol @return string protocol base (including ://)
entailment
protected function _prepColor($color) { if (strpos($color, '#') !== false) { return str_replace('#', '0x', $color); } if (is_numeric($color)) { return '0x' . $color; } return $color; }
// to 0x or // added @param string $color Color: FFFFFF, #FFFFFF, 0xFFFFFF or blue @return string Color
entailment
public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options) { if ($this->_config['on'] === 'beforeMarshal') { $addressfields = (array)$this->_config['address']; $addressData = []; $dirty = false; foreach ($addressfields as $field) { if (!empty($data[$field])) { $addressData[] = $data[$field]; } } if (!$this->_geocode($data, $addressData)) { $event->stopPropagation(); } } }
Using pre-patching to populate the entity with the lat/lng etc before the validation kicks in. This has the downside that it has to run every time. The other events trigger geocoding only if the address data has been modified (fields marked as dirty). @param \Cake\Event\Event $event @param \ArrayObject $data @param \ArrayObject $options @return void
entailment
public function geocode(Entity $entity) { $addressfields = (array)$this->_config['address']; $addressData = []; $dirty = false; foreach ($addressfields as $field) { $fieldData = $entity->get($field); if ($fieldData) { $addressData[] = $fieldData; } if ($entity->isDirty($field)) { $dirty = true; } } if (!$dirty) { if ($this->_config['allowEmpty'] || $entity->lat && $entity->lng) { return $entity; } if ($entity instanceof Entity) { $this->invalidate($entity); } return null; } $result = $this->_geocode($entity, $addressData); if (is_array($result)) { throw new RuntimeException('Array type not expected'); } return $result; }
Run before a model is saved, used to set up slug for model. @param \Geo\Model\Entity\GeocodedAddress $entity The entity that is going to be saved @return \Geo\Model\Entity\GeocodedAddress|null @throws \RuntimeException
entailment
protected function _geocode($entity, array $addressData) { $entityData = [ 'geocoder_result' => [], ]; $search = implode(' ', $addressData); if ($search === '') { if (!$this->_config['allowEmpty']) { return null; } return $entity; } $address = $this->_execute($search); if (!$address) { if ($this->_config['allowEmpty']) { return $entity; } if ($entity instanceof Entity) { $this->invalidate($entity); } return null; } if (!$this->_Geocoder->isExpectedType($address)) { if ($this->_config['allowEmpty']) { return $entity; } if ($entity instanceof Entity) { $this->invalidate($entity); } return null; } // Valid lat/lng found $entityData[$this->_config['lat']] = $address->getLatitude(); $entityData[$this->_config['lng']] = $address->getLongitude(); if (!empty($this->_config['formatted_address'])) { // Unfortunately, the formatted address of google is lost $formatter = new StringFormatter(); $entityData[$this->_config['formatted_address']] = $formatter->format($address, '%S %n, %z %L'); } $entityData['geocoder_result'] = $address->toArray(); $entityData['geocoder_result']['address_data'] = implode(' ', $addressData); if (!empty($this->_config['update'])) { foreach ($this->_config['update'] as $key => $field) { //FIXME, not so easy with the new library if (!empty($geocode[$key])) { $entityData[$field] = $geocode[$key]; } } } foreach ($entityData as $key => $value) { $entity[$key] = $value; } return $entity; }
@param \Geo\Model\Entity\GeocodedAddress|array $entity @param array $addressData @return \Geo\Model\Entity\GeocodedAddress|array|null
entailment
public function findDistance(Query $query, array $options) { $options += ['tableName' => null, 'sort' => true]; $sql = $this->distanceExpr($options['lat'], $options['lng'], null, null, $options['tableName']); if ($query->autoFields() === null) { $query->autoFields(true); } $query->select(['distance' => $query->newExpr($sql)]); if (isset($options['distance'])) { // Some SQL versions cannot reuse the select() distance field, so we better reuse the $sql snippet $query->where(function ($exp) use ($sql, $options) { return $exp->lt($sql, $options['distance']); }); } if ($options['sort']) { $sort = $options['sort'] === true ? 'ASC' : $options['sort']; $query->order(['distance' => $sort]); } return $query; }
Custom finder for distance. Options: - lat (required) - lng (required) - tableName - distance - sort @param \Cake\ORM\Query $query Query. @param array $options Array of options as described above @return \Cake\ORM\Query
entailment
public function distanceExpr($lat, $lng, $fieldLat = null, $fieldLng = null, $tableName = null) { if ($fieldLat === null) { $fieldLat = $this->_config['lat']; } if ($fieldLng === null) { $fieldLng = $this->_config['lng']; } if ($tableName === null) { $tableName = $this->_table->alias(); } $value = $this->_calculationValue($this->_config['unit']); $op = function ($type, $params) { return new QueryExpression($params, [], $type); }; $func = function ($name, $arg = null) { return new FunctionExpression($name, $arg === null ? [] : [$arg]); }; $fieldLat = new IdentifierExpression("$tableName.$fieldLat"); $fieldLng = new IdentifierExpression("$tableName.$fieldLng"); $fieldLatRadians = $func('RADIANS', $op('-', ['90', $fieldLat])); $fieldLngRadians = $func('RADIANS', $fieldLng); $radius = $op('/', [$func('PI'), '2']); $mult = $op('*', [ $func('COS', $op('-', [$radius, $fieldLatRadians])), 'COS(PI()/2 - RADIANS(90 - ' . $lat . '))', $func('COS', $op('-', [$fieldLngRadians, $func('RADIANS', $lng)])), ]); $mult2 = $op('*', [ $func('SIN', $op('-', [$radius, $fieldLatRadians])), $func('SIN', $op('-', [$radius, 'RADIANS(90 - ' . $lat . ')'])), ]); return $op('*', [ (string)$value, $func('ACOS', $op('+', [$mult, $mult2])) ]); }
Forms a sql snippet for distance calculation on db level using two lat/lng points. @param string|float $lat Latitude field (Model.lat) or float value @param string|float $lng Longitude field (Model.lng) or float value @param string|null $fieldLat Comparison field @param string|null $fieldLng Comparison field @param string|null $tableName @return \Cake\Database\ExpressionInterface
entailment
public function distanceConditions($distance = null, $fieldName = null, $fieldLat = null, $fieldLng = null, $tableName = null) { if ($fieldLat === null) { $fieldLat = $this->_config['lat']; } if ($fieldLng === null) { $fieldLng = $this->_config['lng']; } if ($tableName === null) { $tableName = $this->_table->alias(); } $conditions = [ $tableName . '.' . $fieldLat . ' <> 0', $tableName . '.' . $fieldLng . ' <> 0', ]; $fieldName = !empty($fieldName) ? $fieldName : 'distance'; if ($distance !== null) { $conditions[] = '1=1 HAVING ' . $tableName . '.' . $fieldName . ' < ' . (int)$distance; } return $conditions; }
Snippet for custom pagination @param int|null $distance @param string|null $fieldName @param string|null $fieldLat @param string|null $fieldLng @param string|null $tableName @return array
entailment
public function distanceField($lat, $lng, $fieldName = null, $tableName = null) { if ($tableName === null) { $tableName = $this->_table->alias(); } $fieldName = (!empty($fieldName) ? $fieldName : 'distance'); return [$tableName . '.' . $fieldName => $this->distanceExpr($lat, $lng, null, null, $tableName)]; }
Snippet for custom pagination @param float|string $lat @param float|string $lng @param string|null $fieldName @param string|null $tableName @return array
entailment
protected function _execute($address) { /** @var \Geo\Model\Table\GeocodedAddressesTable|null $GeocodedAddresses */ $GeocodedAddresses = null; if ($this->getConfig('cache')) { $GeocodedAddresses = TableRegistry::get('Geo.GeocodedAddresses'); /** @var \Geo\Model\Entity\GeocodedAddress $result */ $result = $GeocodedAddresses->find()->where(['address' => $address])->first(); if ($result) { /** @var \Geocoder\Model\Address|null $data */ $data = $result->data; return $data ?: null; } } try { $addresses = $this->_Geocoder->geocode($address); } catch (InconclusiveException $e) { $addresses = null; } catch (NotAccurateEnoughException $e) { $addresses = null; } $result = null; if ($addresses && $addresses->count() > 0) { $result = $addresses->first(); } if ($this->getConfig('cache')) { /** @var \Geo\Model\Entity\GeocodedAddress $addressEntity */ $addressEntity = $GeocodedAddresses->newEntity([ 'address' => $address ]); if ($result) { $formatter = new StringFormatter(); $addressEntity->formatted_address = $formatter->format($result, '%S %n, %z %L'); $addressEntity->lat = $result->getLatitude(); $addressEntity->lng = $result->getLongitude(); $addressEntity->country = $result->getCountry()->getCode(); $addressEntity->data = $result; } if (!$GeocodedAddresses->save($addressEntity, ['atomic' => false])) { throw new RuntimeException('Could not store geocoding cache data'); } } return $result; }
Uses the Geocode class to query @param string $address @return \Geocoder\Model\Address|null @throws \RuntimeException
entailment
protected function _calculationValue($unit) { if (!isset($this->_Calculator)) { $this->_Calculator = new Calculator(); } return $this->_Calculator->convert(6371.04, Calculator::UNIT_KM, $unit); }
Get the current unit factor @param int $unit Unit constant @return float Value
entailment
public function geocode($address, array $params = []) { $this->_buildGeocoder(); try { $result = $this->geocoder->geocode($address); } catch (NoResult $e) { throw new InconclusiveException(sprintf('Inconclusive result (total of %s)', 0)); } if (!$this->_config['allowInconclusive'] && !$this->isConclusive($result)) { throw new InconclusiveException(sprintf('Inconclusive result (total of %s)', $result->count())); } if ($this->_config['minAccuracy'] && !$this->containsAccurateEnough($result)) { throw new NotAccurateEnoughException('Result is not accurate enough'); } return $result; }
Actual querying. The query will be flatted, and if multiple results are fetched, they will be found in $result['all']. @param string $address @param array $params @return \Geocoder\Model\AddressCollection Result
entailment
public function reverse($lat, $lng, array $params = []) { $this->_buildGeocoder(); $result = $this->geocoder->reverse($lat, $lng); if (!$this->_config['allowInconclusive'] && !$this->isConclusive($result)) { throw new InconclusiveException(sprintf('Inconclusive result (total of %s)', $result->count())); } if ($this->_config['minAccuracy'] && !$this->containsAccurateEnough($result)) { throw new NotAccurateEnoughException('Result is not accurate enough'); } return $result; }
Results usually from most accurate to least accurate result (street_address, ..., country) @param float $lat @param float $lng @param array $params @return \Geocoder\Model\AddressCollection Result
entailment
public function isExpectedType(Address $address) { $expected = $this->_config['expect']; if (!$expected) { return true; } $adminLevels = $address->getAdminLevels(); $map = [ static::TYPE_AAL1 => 1, static::TYPE_AAL2 => 2, static::TYPE_AAL3 => 3, static::TYPE_AAL4 => 4, static::TYPE_AAL5 => 5, ]; foreach ($expected as $expect) { switch ($expect) { case static::TYPE_COUNTRY: if ($address->getCountry() !== null) { return true; } break; case (static::TYPE_AAL1): case (static::TYPE_AAL2): case (static::TYPE_AAL3): case (static::TYPE_AAL4): case (static::TYPE_AAL5): if ($adminLevels->has($map[$expect])) { return true; } break; case static::TYPE_LOC: if ($address->getLocality() !== null) { return true; } break; case static::TYPE_SUBLOC: if ($address->getSubLocality() !== null) { return true; } break; case static::TYPE_POSTAL: if ($address->getPostalCode() !== null) { return true; } break; case static::TYPE_ADDRESS: if ($address->getStreetName() !== null) { return true; } break; case static::TYPE_NUMBER: if ($address->getStreetNumber() !== null) { return true; } break; } } return false; }
Expects certain address types to be present in the given address. @param \Geocoder\Model\Address $address @return bool
entailment
public function marshal($value) { if ($value === null) { return $value; } if (is_object($value)) { return $value; } return unserialize($value); }
@param object|string|null $value @return object|null
entailment
public function convert($value, $fromUnit, $toUnit) { $fromUnit = strtoupper($fromUnit); $toUnit = strtoupper($toUnit); if (!isset($this->_units[$fromUnit]) || !isset($this->_units[$toUnit])) { throw new CalculatorException('Invalid Unit'); } if ($fromUnit === static::UNIT_MILES) { $value *= $this->_units[$toUnit]; } elseif ($toUnit === static::UNIT_MILES) { $value /= $this->_units[$fromUnit]; } else { $value /= $this->_units[$fromUnit]; $value *= $this->_units[$toUnit]; } return $value; }
Convert between units @param float $value @param string $fromUnit (using class constants) @param string $toUnit (using class constants) @return float convertedValue @throws \Exception
entailment
public function distance(array $pointX, array $pointY, $unit = null) { if (empty($unit)) { $unit = array_keys($this->_units); $unit = $unit[0]; } $unit = strtoupper($unit); if (!isset($this->_units[$unit])) { throw new CalculatorException(sprintf('Invalid Unit: %s', $unit)); } $res = $this->calculateDistance($pointX, $pointY); if (isset($this->_units[$unit])) { $res *= $this->_units[$unit]; } return ceil($res); }
Calculates Distance between two points - each: array('lat'=>x,'lng'=>y) DB: '6371.04 * ACOS( COS( PI()/2 - RADIANS(90 - Retailer.lat)) * ' . 'COS( PI()/2 - RADIANS(90 - '. $data['Location']['lat'] .')) * ' . 'COS( RADIANS(Retailer.lng) - RADIANS('. $data['Location']['lng'] .')) + ' . 'SIN( PI()/2 - RADIANS(90 - Retailer.lat)) * ' . 'SIN( PI()/2 - RADIANS(90 - '. $data['Location']['lat'] . '))) ' . 'AS distance' @param array $pointX @param array $pointY @param string|null $unit Unit char or constant (M=miles, K=kilometers, N=nautical miles, I=inches, F=feet) @return int Distance in km
entailment
public static function calculateDistance($pointX, $pointY) { $res = 69.09 * rad2deg(acos(sin(deg2rad($pointX['lat'])) * sin(deg2rad($pointY['lat'])) + cos(deg2rad($pointX['lat'])) * cos(deg2rad($pointY['lat'])) * cos(deg2rad($pointX['lng'] - $pointY['lng'])))); return $res; }
Geocoder::calculateDistance() @param array|\ArrayObject $pointX @param array|\ArrayObject $pointY @return float
entailment
public static function blur($coordinate, $level = 0) { if (!$level) { return $coordinate; } $scrambleVal = 0.000001 * mt_rand(10, 200) * pow(2, $level) * (mt_rand(0, 1) === 0 ? 1 : -1); return $coordinate + $scrambleVal; //$scrambleVal *= (float)(2^$level); // TODO: + - by chance!!! }
Fuzziness filter for coordinates (lat or lng). Useful if you store other users' locations and want to grant some privacy protection. This way the coordinates will be slightly modified. @param float $coordinate Coordinate @param int $level The Level of blurriness (0...n), 0 means no blur @return float Coordinates @throws \Exception
entailment
public function handle($request, Closure $next, $group) { if ($this->auth->check() && $this->auth->user()->group() == $group) { return $next($request); } throw new GroupDeniedException($group); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @param int $group @return mixed @throws \HttpOz\Roles\Exceptions\GroupDeniedException
entailment
public function object($data = [], $options = []) { $defaultOptions = [ 'prefix' => '', 'postfix' => '', ]; $options += $defaultOptions; return $options['prefix'] . json_encode($data) . $options['postfix']; }
Generates a JavaScript object in JavaScript Object Notation (JSON) from an array. Will use native JSON encode method if available, and $useNative == true ### Options: - `prefix` - String prepended to the returned data. - `postfix` - String appended to the returned data. @param array $data Data to be converted. @param array $options Set of options, see above. @return string A JSON code block
entailment
public function value($val = [], $quoteString = null, $key = 'value') { if ($quoteString === null) { $quoteString = true; } switch (true) { case (is_array($val) || is_object($val)): $val = $this->object($val); break; case ($val === null): $val = 'null'; break; case (is_bool($val)): $val = ($val === true) ? 'true' : 'false'; break; case (is_int($val)): break; case (is_float($val)): $val = sprintf('%.11f', $val); break; default: $val = $this->escape($val); if ($quoteString) { $val = '"' . $val . '"'; } } return $val; }
Converts a PHP-native variable of any type to a JSON-equivalent representation @param mixed $val A PHP variable to be converted to JSON @param bool|null $quoteString If false, leaves string values unquoted @param string $key Key name. @return string a JavaScript-safe/JSON representation of $val
entailment
protected function _utf8ToHex($string) { $length = strlen($string); $return = ''; for ($i = 0; $i < $length; ++$i) { $ord = ord($string{$i}); switch (true) { case $ord == 0x08: $return .= '\b'; break; case $ord == 0x09: $return .= '\t'; break; case $ord == 0x0A: $return .= '\n'; break; case $ord == 0x0C: $return .= '\f'; break; case $ord == 0x0D: $return .= '\r'; break; case $ord == 0x22: case $ord == 0x2F: case $ord == 0x5C: $return .= '\\' . $string{$i}; break; case (($ord >= 0x20) && ($ord <= 0x7F)): $return .= $string{$i}; break; case (($ord & 0xE0) == 0xC0): if ($i + 1 >= $length) { $i += 1; $return .= '?'; break; } $charbits = $string{$i} . $string{$i + 1}; $char = static::utf8($charbits); $return .= sprintf('\u%04s', dechex($char[0])); $i += 1; break; case (($ord & 0xF0) == 0xE0): if ($i + 2 >= $length) { $i += 2; $return .= '?'; break; } $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2}; $char = static::utf8($charbits); $return .= sprintf('\u%04s', dechex($char[0])); $i += 2; break; case (($ord & 0xF8) == 0xF0): if ($i + 3 >= $length) { $i += 3; $return .= '?'; break; } $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3}; $char = static::utf8($charbits); $return .= sprintf('\u%04s', dechex($char[0])); $i += 3; break; case (($ord & 0xFC) == 0xF8): if ($i + 4 >= $length) { $i += 4; $return .= '?'; break; } $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3} . $string{$i + 4}; $char = static::utf8($charbits); $return .= sprintf('\u%04s', dechex($char[0])); $i += 4; break; case (($ord & 0xFE) == 0xFC): if ($i + 5 >= $length) { $i += 5; $return .= '?'; break; } $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3} . $string{$i + 4} . $string{$i + 5}; $char = static::utf8($charbits); $return .= sprintf('\u%04s', dechex($char[0])); $i += 5; break; } } return $return; }
Encode a string into JSON. Converts and escapes necessary characters. @param string $string The string that needs to be utf8->hex encoded @return string
entailment
protected function _parseOptions($options, $safeKeys = []) { $out = []; $safeKeys = array_flip($safeKeys); foreach ($options as $key => $value) { if (!is_int($value) && !isset($safeKeys[$key])) { $value = $this->value($value); } $out[] = $key . ':' . $value; } sort($out); return implode(', ', $out); }
Parse an options assoc array into a JavaScript object literal. Similar to object() but treats any non-integer value as a string, does not include `{ }` @param array $options Options to be converted @param array $safeKeys Keys that should not be escaped. @return string Parsed JSON options without enclosing { }.
entailment
protected function _prepareCallbacks($method, $options, $callbacks = []) { $wrapCallbacks = true; if (isset($options['wrapCallbacks'])) { $wrapCallbacks = $options['wrapCallbacks']; } unset($options['wrapCallbacks']); if (!$wrapCallbacks) { return $options; } $callbackOptions = []; if (isset($this->_callbackArguments[$method])) { $callbackOptions = $this->_callbackArguments[$method]; } $callbacks = array_unique(array_merge(array_keys($callbackOptions), (array)$callbacks)); foreach ($callbacks as $callback) { if (empty($options[$callback])) { continue; } $args = null; if (!empty($callbackOptions[$callback])) { $args = $callbackOptions[$callback]; } $options[$callback] = 'function (' . $args . ') {' . $options[$callback] . '}'; } return $options; }
Prepare callbacks and wrap them with function ([args]) { } as defined in _callbackArgs array. @param string $method Name of the method you are preparing callbacks for. @param array $options Array of options being parsed @param array $callbacks Additional Keys that contain callbacks @return array Array of options with callbacks added.
entailment
protected function _processOptions($method, $options) { $options = $this->_mapOptions(); $options = $this->_prepareCallbacks($method, $options); $options = $this->_parseOptions($options, array_keys($this->_callbackArguments[$method])); return $options; }
Convenience wrapper method for all common option processing steps. Runs _mapOptions, _prepareCallbacks, and _parseOptions in order. @param string $method Name of method processing options for. @param array $options Array of options to process. @return string Parsed options string.
entailment
protected function _toQuerystring($parameters) { $out = ''; $keys = array_keys($parameters); $count = count($parameters); for ($i = 0; $i < $count; $i++) { $out .= $keys[$i] . '=' . $parameters[$keys[$i]]; if ($i < $count - 1) { $out .= '&'; } } return $out; }
Convert an array of data into a query string @param array $parameters Array of parameters to convert to a query string @return string Querystring fragment
entailment
protected static function utf8($string) { $map = []; $values = []; $find = 1; $length = strlen($string); for ($i = 0; $i < $length; $i++) { $value = ord($string[$i]); if ($value < 128) { $map[] = $value; } else { if (empty($values)) { $find = ($value < 224) ? 2 : 3; } $values[] = $value; if (count($values) === $find) { if ($find == 3) { $map[] = (($values[0] % 16) * 4096) + (($values[1] % 64) * 64) + ($values[2] % 64); } else { $map[] = (($values[0] % 32) * 64) + ($values[1] % 64); } $values = []; $find = 1; } } } return $map; }
Converts a multibyte character string to the decimal value of the character @param string $string String to convert. @return array
entailment
public function getResponseHeader($header) { if (! isset($this->responseHeaders[$header])) { throw new \InvalidArgumentException('Header does not exist'); } return $this->responseHeaders[$header]; }
@param string $header @return string
entailment
protected function parseGet($url, $query) { $append = strpos($url, '?') === false ? '?' : '&'; return $url . $append . http_build_query($query); }
Appends query array onto URL @param string $url @param array $query @return string
entailment
protected function request($url, $parameters = array(), $request = false) { $this->lastRequest = $url; $this->lastRequestData = $parameters; $this->responseHeaders = array(); $curl = curl_init($url); $curlOptions = array( CURLOPT_SSL_VERIFYPEER => false, CURLOPT_REFERER => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADERFUNCTION => array($this, 'parseHeader'), ); if (! empty($parameters) || ! empty($request)) { if (! empty($request)) { $curlOptions[ CURLOPT_CUSTOMREQUEST ] = $request; $parameters = http_build_query($parameters); } else { $curlOptions[ CURLOPT_POST ] = true; } $curlOptions[ CURLOPT_POSTFIELDS ] = $parameters; } curl_setopt_array($curl, $curlOptions); $response = curl_exec($curl); $error = curl_error($curl); $this->lastRequestInfo = curl_getinfo($curl); curl_close($curl); if (! empty($error)) { throw new \Exception($error); } return $this->parseResponse($response); }
Makes HTTP Request to the API @param string $url @param array $parameters @param bool|string $request the request method, default is POST @return mixed @throws \Exception
entailment
public function authenticationUrl($redirect, $approvalPrompt = 'auto', $scope = null, $state = null) { $parameters = array( 'client_id' => $this->clientId, 'redirect_uri' => $redirect, 'response_type' => 'code', 'approval_prompt' => $approvalPrompt, 'state' => $state, ); if (! is_null($scope)) { $parameters['scope'] = $scope; } return $this->parseGet( $this->authUrl . 'authorize', $parameters ); }
Creates authentication URL for your app @param string $redirect @param string $approvalPrompt @param string $scope @param string $state @link http://strava.github.io/api/v3/oauth/#get-authorize @return string
entailment
public function tokenExchange($code) { $parameters = array( 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret, 'code' => $code, ); return $this->request( $this->authUrl . 'token', $parameters ); }
Authenticates token returned from API @param string $code @link http://strava.github.io/api/v3/oauth/#post-token @return string
entailment
public function get($request, $parameters = array()) { $parameters = $this->generateParameters($parameters); $requestUrl = $this->parseGet($this->getAbsoluteUrl($request), $parameters); return $this->request($requestUrl); }
Sends GET request to specified API endpoint @param string $request @param array $parameters @example http://strava.github.io/api/v3/athlete/#koms @return string
entailment
public function put($request, $parameters = array()) { return $this->request( $this->getAbsoluteUrl($request), $this->generateParameters($parameters), 'PUT' ); }
Sends PUT request to specified API endpoint @param string $request @param array $parameters @example http://strava.github.io/api/v3/athlete/#update @return string
entailment
public function post($request, $parameters = array()) { return $this->request( $this->getAbsoluteUrl($request), $this->generateParameters($parameters) ); }
Sends POST request to specified API endpoint @param string $request @param array $parameters @example http://strava.github.io/api/v3/activities/#create @return string
entailment
public function delete($request, $parameters = array()) { return $this->request( $this->getAbsoluteUrl($request), $this->generateParameters($parameters), 'DELETE' ); }
Sends DELETE request to specified API endpoint @param string $request @param array $parameters @example http://strava.github.io/api/v3/activities/#delete @return string
entailment
protected function parseHeader($curl, $headerLine) { $size = strlen($headerLine); $trimmed = trim($headerLine); // skip empty line(s) if (empty($trimmed)) { return $size; } // skip first header line (HTTP status code) if (strpos($trimmed, 'HTTP/') === 0) { return $size; } $parts = explode(':', $headerLine); $key = array_shift($parts); $value = implode(':', $parts); $this->responseHeaders[$key] = trim($value); return $size; }
Parses the header lines into the $responseHeaders attribute Skips the first header line (HTTP response status) and the last header line (empty). @param resource $curl @param string $headerLine @return int length of the currently parsed header line in bytes
entailment
protected function getAbsoluteUrl($request) { $request = ltrim($request); if (strpos($request, 'http') === 0) { return $request; } return $this->apiUrl . $request; }
Checks the given request string and returns the absolute URL to make the necessary API call @param string $request @return string
entailment
public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $kernelRootDir = $container->getParameter('kernel.root_dir'); $directoryList = []; foreach ($config['directories'] as $pattern) { list($classes, $directories) = $this->getClasses($this->getDirectory($kernelRootDir, $pattern)); $directoryList = array_merge($directoryList, $directories); foreach ($classes as $class) { $this->registerClass($container, $class, $config['tags'], $config['methods']); } } $directories = []; foreach ($directoryList as $directory => $v) { $directory = realpath($directory); $container->addResource(new DirectoryResource($directory, '/\.php$/')); $directories[$directory] = true; } $container->setParameter('dunglas_action.directories', $directories); }
{@inheritdoc}
entailment
private function getDirectory($kernelRootDir, $pattern) { $firstCharacter = substr($pattern, 0, 1); if ('/' === $firstCharacter || DIRECTORY_SEPARATOR === $firstCharacter) { return $pattern; } return $kernelRootDir.DIRECTORY_SEPARATOR.$pattern; }
@param string $kernelRootDir @param string $pattern @return string
entailment
private function getClasses($directory) { $classes = []; $directoryList = []; $includedFiles = []; $finder = new Finder(); try { $finder->in($directory)->files()->name('*.php'); } catch (\InvalidArgumentException $e) { return [[], []]; } foreach ($finder as $file) { $directoryList[$file->getPath()] = true; $sourceFile = $file->getRealpath(); if (!preg_match('(^phar:)i', $sourceFile)) { $sourceFile = realpath($sourceFile); } require_once $sourceFile; $includedFiles[$sourceFile] = true; } $declared = get_declared_classes(); foreach ($declared as $className) { $reflectionClass = new \ReflectionClass($className); $sourceFile = $reflectionClass->getFileName(); if ($reflectionClass->isAbstract()) { continue; } if (method_exists($reflectionClass, 'isAnonymous') && $reflectionClass->isAnonymous()) { continue; } if (isset($includedFiles[$sourceFile])) { $classes[$className] = true; } } return [array_keys($classes), $directoryList]; }
Gets the list of class names in the given directory. @param string $directory @return array
entailment
private function registerClass(ContainerBuilder $container, $className, array $tags, array $methods) { if ($container->has($className)) { return; } $definition = $container->register($className, $className); if (method_exists($definition, 'setAutowiredMethods')) { $definition->setAutowiredMethods($methods); } else { $definition->setAutowired(true); } // Inject the container if applicable if (is_a($className, ContainerAwareInterface::class, true)) { $definition->addMethodCall('setContainer', [new Reference('service_container')]); } foreach ($tags as $tagClassName => $classTags) { if (!is_a($className, $tagClassName, true)) { continue; } foreach ($classTags as $classTag) { $definition->addTag($classTag[0], $classTag[1]); } } }
Registers an action in the container. @param ContainerBuilder $container @param string $className @param array $tags @param string[] $methods
entailment
public function fire() { $structure = __DIR__ . '/../../../../structure'; $base = base_path(); $this->line('<info>codesleeve\asset-pipeline creating initial directory structure and copying some general purpose assets over</info>'); $this->xcopy(realpath($structure), realpath($base)); $this->line(''); $this->line('<info>codesleeve\asset-pipeline completed directory setup</info>'); }
Execute the console command. @return void
entailment
public function register() { $this->package('codesleeve/asset-pipeline'); include_once __DIR__.'/AssetPipelineGlobalHelpers.php'; $this->app['asset'] = $this->app->share(function($app) { $config = $app->config->get('asset-pipeline::config'); $config['base_path'] = base_path(); $config['environment'] = $app['env']; $parser = new SprocketsParser($config); $generator = new SprocketsGenerator($config); $pipeline = new AssetPipeline($parser, $generator); // let other packages hook into pipeline configuration $app['events']->fire('asset.pipeline.boot', $pipeline); return $pipeline->registerAssetPipelineFilters(); }); $this->app['assets.setup'] = $this->app->share(function($app) { return new Commands\AssetsSetupCommand; }); $this->app['assets.clean'] = $this->app->share(function($app) { return new Commands\AssetsCleanCommand; }); $this->app['assets.generate'] = $this->app->share(function($app) { return new Commands\AssetsGenerateCommand; }); $this->commands('assets.setup'); $this->commands('assets.clean'); $this->commands('assets.generate'); }
Register the service provider. @return void
entailment
protected function registerBladeExtensions() { $blade = $this->app['view']->getEngineResolver()->resolve('blade')->getCompiler(); $blade->extend(function($value, $compiler) { $matcher = $compiler->createMatcher('javascripts'); return preg_replace($matcher, '$1<?php echo javascript_include_tag$2; ?>', $value); }); $blade->extend(function($value, $compiler) { $matcher = $compiler->createMatcher('stylesheets'); return preg_replace($matcher, '$1<?php echo stylesheet_link_tag$2; ?>', $value); }); }
Register custom blade extensions - @stylesheets() - @javascripts() @return void
entailment
public function fire() { $asset = \App::make('asset'); // we need to turn on concatenation // since we are spitting out assets $config = $asset->getConfig(); $config['environment'] = $this->option('env') ? : 'production'; $asset->setConfig($config); $generator = new StaticFilesGenerator($asset->getGenerator()); $generated = $generator->generate(public_path($config['routing']['prefix'])); foreach ($generated as $file) { $this->line($file); } $this->line('<info>codesleeve\asset-pipeline assets generated! :)</info>'); }
Execute the console command. @return void
entailment
public function file($path) { $absolutePath = Asset::isJavascript($path); if ($absolutePath) { return $this->javascript($absolutePath); } $absolutePath = Asset::isStylesheet($path); if ($absolutePath) { return $this->stylesheet($absolutePath); } $absolutePath = Asset::isFile($path); if ($absolutePath) { $this->clientCacheForFile($absolutePath); return new BinaryFileResponse($absolutePath, 200); } App::abort(404); }
Returns a file in the assets directory @return \Illuminate\Support\Facades\Response
entailment
private function javascript($path) { $response = Response::make(Asset::javascript($path), 200); $response->header('Content-Type', 'application/javascript'); return $response; }
/* Returns a javascript file for the given path. @return \Illuminate\Support\Facades\Response
entailment
private function stylesheet($path) { $response = Response::make(Asset::stylesheet($path), 200); $response->header('Content-Type', 'text/css'); return $response; }
Returns css for the given path @return \Illuminate\Support\Facades\Response
entailment
private function clientCacheForFile($path) { $lastModified = filemtime($path); if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $lastModified) { header('HTTP/1.0 304 Not Modified'); exit; } }
Client cache regular files that are not javascript or stylesheets files @param string $path @return void
entailment
public function get($key) { $lastModified = $this->getLastTimeModified($key); $modifiedSince = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : 0; header('Last-Modified: '. $lastModified); if ($modifiedSince >= $lastModified) { header('HTTP/1.0 304 Not Modified'); exit; } return $this->cache->get($key); }
If we make it here then we have a cached version of this asset found in the underlying $cache driver. So we will check the header HTTP_IF_MODIFIED_SINCE and if that is not less than the last time we cached ($lastModified) then we will exit with 304 header. @param string $key @return string
entailment
protected function attributesArrayToText($attributes) { $text = ""; foreach ($attributes as $name => $value) { $text .= "{$name}=\"{$value}\" "; } $text = rtrim($text); return $text; }
Convert the attributes array to a html text attributes @param array $attributes @return string
entailment
public function url_matcher($matches) { list($changed, $newurl) = $this->relative_match($matches['url']); if ($changed) { return str_replace($matches['url'], $newurl, $matches[0]); } list($changed, $newurl) = $this->found_file_match($matches['url']); if ($changed) { return str_replace($matches['url'], $newurl, $matches[0]); } return $matches[0]; }
My attempt at rewriting CSS urls. I am looking for all url tags and then I am going to try and resolve the correct absolute path from those urls. If the file actually exists then we are good, else I just leave the thing alone. @param [type] $matches [description] @return [type] [description]
entailment
public function relative_match($url) { $changed = false; $base = $this->base; $root = $this->root; while (0 === strpos($url, '../') && 2 <= substr_count($base, '/')) { $changed = true; $base = substr($base, 0, strrpos(rtrim($base, '/'), '/') + 1); $root = substr($root, 0, strrpos(rtrim($root, '/'), '/') + 1); $url = substr($url, 3); } if (!$changed || !$this->fileExists($root . $url)) { return array(false, $url); } return array(true, $this->baseurl . $this->prefix . $base . $url); }
Search for cases like url(../fonts/blah.eot) @param string $url @return array(bool, string)
entailment
public function found_file_match($url) { if ($url[0] != '/' && $this->fileExists($this->root . $url)) { return array(true, $this->baseurl . $this->prefix . $this->base . $url); } return array(false, $url); }
Search for the case where we might be concatenating and so long as the url doesn't start with a '/' we will see if there is a file relative to this directory. @param string $url @return array(bool, string)
entailment
public function fire() { $recursive = $this->option('recursive') === true; $this->verbose = $this->option('verbose') === true; $files = $this->option('file'); foreach ($files as $file) { $this->removeAssetCache($file, $recursive); } $this->line('<info>codesleeve/asset-pipeline cache cleared!</info>'); $this->line('<info>Cache will be re-built on next page request.</info>'); }
Execute the console command. @return void
entailment
protected function removeAssetCache($file, $recursive) { $files = $this->asset->isJavascript($file) ? $this->asset->getParser()->javascriptFiles($file) : $this->asset->getParser()->stylesheetFiles($file); array_push($files, $this->asset->getParser()->absoluteFilePath($file)); foreach ($files as $file) { $removed = $this->asset->getGenerator()->cachedFile($file)->remove(); if ($removed === false) { $this->writeln(PHP_EOL . "<warning> failed to find/remove cache for {$file}</warning>"); } } }
Removes the AssetCache for this file @param [type] $file [description] @param [type] $recursive [description] @return [type] [description]
entailment
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $treeBuilder->root('dunglas_action') ->fixXmlConfig('directory', 'directories') ->children() ->arrayNode('methods') ->info('The list of methods to autowire.') ->prototype('scalar')->end() ->defaultValue(['__construct', 'get*', 'set*']) ->end() ->arrayNode('directories') ->info('List of directories relative to the kernel root directory containing classes.') ->prototype('scalar')->end() ->defaultValue([ '../src/*Bundle/Action', '../src/*Bundle/Command', '../src/*Bundle/Controller', '../src/*Bundle/EventSubscriber', '../src/*Bundle/Twig', ]) ->end() ->arrayNode('tags') ->info('List of tags to add when implementing the corresponding class.') ->useAttributeAsKey('class') ->prototype('array') // Converts 'console.command' to ['console.command'] ->beforeNormalization()->ifString()->then(function ($v) { return [$v]; })->end() ->prototype('array') // Converts 'console.command' to ['console.command', []] ->beforeNormalization()->ifString()->then(function ($v) { return [$v, []]; })->end() ->validate() ->ifTrue(function ($v) { return count($v) !== 2 || !is_string($v[0]) || !is_array($v[1]); }) ->thenInvalid('Invalid tag format. They must be as following: [\'my_tag.name\', [\'attribute\' => \'value\']]') ->end() ->prototype('variable')->end() ->end() ->end() ->defaultValue([ Command::class => [['console.command', []]], EventSubscriberInterface::class => [['kernel.event_subscriber', []]], \Twig_ExtensionInterface::class => [['twig.extension', []]], ]) ->end() ->end() ->end(); return $treeBuilder; }
{@inheritdoc}
entailment
public function javascriptIncludeTag($filename, $attributes) { $webPaths = array(); $absolutePaths = $this->parser->javascriptFiles($filename); foreach ($absolutePaths as $absolutePath) { $webPaths[] = $this->parser->absolutePathToWebPath($absolutePath); } $config = $this->getConfig(); $composer = $config['javascript_include_tag']; return $composer->process($webPaths, $absolutePaths, $attributes); }
Create javascript include tag(s) @param string $filename @param array $attributes @return string
entailment
public function stylesheetLinkTag($filename, $attributes) { $webPaths = array(); $absolutePaths = $this->parser->stylesheetFiles($filename); foreach ($absolutePaths as $absolutePath) { $webPaths[] = $this->parser->absolutePathToWebPath($absolutePath); } $config = $this->getConfig(); $composer = $config['stylesheet_link_tag']; return $composer->process($webPaths, $absolutePaths, $attributes); }
Create stylesheet link tag(s) @param string $filename @param array $attributes @return string
entailment
public function imageTag($filename, $attributes) { $absolutePath = $this->file($filename); $webPath = $this->parser->absolutePathToWebPath($absolutePath); $config = $this->getConfig(); $composer = $config['image_tag']; return $composer->process(array($webPath), array($absolutePath), $attributes); }
Create image tag @param string $filename @param array $attributes @return string
entailment
public function isFile($filename) { $absolutePath = $this->parser->absoluteFilePath($filename); return file_exists($absolutePath) && is_file($absolutePath) ? $absolutePath : null; }
Is this filename any type of file? @param string $filename @return boolean
entailment
public function setConfig(array $config) { $this->parser->config = $config; $this->generator->config = $config; $this->registerAssetPipelineFilters(); }
Set the config array @param array $config
entailment
public function registerAssetPipelineFilters() { foreach ($this->parser->config['filters'] as $filters) { foreach ($filters as $filter) { if (method_exists($filter, 'setAssetPipeline')) { $filter->setAssetPipeline($this); } } } foreach ($this->generator->config['filters'] as $filters) { foreach ($filters as $filter) { if (method_exists($filter, 'setAssetPipeline')) { $filter->setAssetPipeline($this); } } } return $this; }
This calls a method on every filter we have to pass in the current pipeline if that method exists @return void
entailment
public function process($paths, $absolutePaths, $attributes) { $url = url(); $attributesAsText = $this->attributesArrayToText($attributes); foreach ($paths as $path) { print "<link href=\"{$url}{$path}\" {$attributesAsText} rel=\"stylesheet\" type=\"text/css\">" . PHP_EOL; } }
Process the paths that come through the asset pipeline @param array $paths @param array $absolutePaths @param array $attributes @return void
entailment
public function compileMap(ResolverInterface $resolver) : array { if ($resolver instanceof AggregateResolver) { return $this->compileFromAggregateResolver($resolver); } if ($resolver instanceof TemplatePathStack) { return $this->compileFromTemplatePathStack($resolver); } if ($resolver instanceof TemplateMapResolver) { return $this->compileFromTemplateMapResolver($resolver); } return []; }
Generates a list of all existing templates in the given resolver, with their names being keys, and absolute paths being values @param ResolverInterface $resolver @return array @throws \Zend\View\Exception\DomainException
entailment
protected function compileFromTemplatePathStack(TemplatePathStack $resolver) : array { $map = []; foreach ($resolver->getPaths()->toArray() as $path) { $path = realpath($path); $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::LEAVES_ONLY ); foreach ($iterator as $file) { $this->addResolvedPath($file, $map, $path, $resolver); } } return $map; }
@param TemplatePathStack $resolver @return array @throws \Zend\View\Exception\DomainException
entailment
private function addResolvedPath(SplFileInfo $file, array & $map, $basePath, TemplatePathStack $resolver) { $filePath = $file->getRealPath(); $fileName = pathinfo($filePath, PATHINFO_FILENAME); $relativePath = trim(str_replace($basePath, '', $file->getPath()), '/\\'); $templateName = str_replace('\\', '/', trim($relativePath . '/' . $fileName, '/')); if ($fileName && ($resolvedPath = $resolver->resolve($templateName))) { $map[$templateName] = realpath($resolvedPath); } }
Add the given file to the map if it corresponds to a resolved view @param SplFileInfo $file @param array $map @param string $basePath @param TemplatePathStack $resolver @return void @throws \Zend\View\Exception\DomainException
entailment
public function resolve($name, RendererInterface $renderer = null) { if (isset($this->map[$name])) { return $this->map[$name]; } if (null !== $this->map) { return false; } $this->loadMap(); return $this->resolve($name); }
{@inheritDoc}
entailment
private function loadMap() { $this->map = $this->cache->getItem($this->cacheKey); if (is_array($this->map)) { return; } $realResolverInstantiator = $this->realResolverInstantiator; $realResolver = $realResolverInstantiator(); if (! $realResolver instanceof ResolverInterface) { throw InvalidResolverInstantiatorException::fromInvalidResolver($realResolver); } $this->map = (new TemplateMapCompiler())->compileMap($realResolver); $this->cache->setItem($this->cacheKey, $this->map); }
Load the template map into memory
entailment
public function resolve($name, RendererInterface $renderer = null) { if (! $this->resolver) { $resolverInstantiator = $this->resolverInstantiator; $resolver = $resolverInstantiator(); if (! $resolver instanceof ResolverInterface) { throw InvalidResolverInstantiatorException::fromInvalidResolver($resolver); } $this->resolver = $resolver; } return $this->resolver->resolve($name, $renderer); }
{@inheritDoc}
entailment
public static function fromInvalidInstantiator($instantiator) : self { return new self(sprintf( 'Invalid instantiator given, expected `callable`, `%s` given.', is_object($instantiator) ? get_class($instantiator) : gettype($instantiator) )); }
@param mixed $instantiator @return self
entailment
public static function fromInvalidResolver($resolver) : self { return new self(sprintf( 'Invalid resolver found, expected `' . ResolverInterface::class . '`, `%s` given.', is_object($resolver) ? get_class($resolver) : gettype($resolver) )); }
@param mixed $resolver @return self
entailment
public function getConfig() : array { return [ self::CONFIG => [ self::CONFIG_CACHE_DEFINITION => ['adapter' => Apc::class], self::CONFIG_CACHE_KEY => 'cached_template_map', self::CONFIG_CACHE_SERVICE => 'OcraCachedViewResolver\\Cache\\DummyCache', ], 'service_manager' => [ 'invokables' => ['OcraCachedViewResolver\\Cache\\DummyCache' => BlackHole::class], 'factories' => ['OcraCachedViewResolver\\Cache\\ResolverCache' => CacheFactory::class], 'delegators' => [ 'ViewResolver' => [ CompiledMapResolverDelegatorFactory::class => CompiledMapResolverDelegatorFactory::class, ], ], ], ]; }
{@inheritDoc}
entailment
public function encode(string $data): string { if (true === $this->options["check"]) { $data = chr($this->options["version"]) . $data; $hash = hash("sha256", $data, true); $hash = hash("sha256", $hash, true); $checksum = substr($hash, 0, 4); $data .= $checksum; } $data = str_split($data); $data = array_map("ord", $data); $leadingZeroes = 0; while (!empty($data) && 0 === $data[0]) { $leadingZeroes++; array_shift($data); } $converted = $this->baseConvert($data, 256, 58); if (0 < $leadingZeroes) { $converted = array_merge( array_fill(0, $leadingZeroes, 0), $converted ); } return implode("", array_map(function ($index) { return $this->options["characters"][$index]; }, $converted)); }
Encode given data to a base58 string
entailment
public function decode(string $data): string { $this->validateInput($data); $data = str_split($data); $data = array_map(function ($character) { return strpos($this->options["characters"], $character); }, $data); $leadingZeroes = 0; while (!empty($data) && 0 === $data[0]) { $leadingZeroes++; array_shift($data); } $converted = $this->baseConvert($data, 58, 256); if (0 < $leadingZeroes) { $converted = array_merge( array_fill(0, $leadingZeroes, 0), $converted ); } $decoded = implode("", array_map("chr", $converted)); if (true === $this->options["check"]) { $hash = substr($decoded, 0, -(Base58::CHECKSUM_SIZE)); $hash = hash("sha256", $hash, true); $hash = hash("sha256", $hash, true); $checksum = substr($hash, 0, Base58::CHECKSUM_SIZE); if (0 !== substr_compare($decoded, $checksum, -(Base58::CHECKSUM_SIZE))) { $message = sprintf( 'Checksum "%s" does not match the expected "%s"', bin2hex(substr($decoded, -(Base58::CHECKSUM_SIZE))), bin2hex($checksum) ); throw new RuntimeException($message); } $version = substr($decoded, 0, Base58::VERSION_SIZE); $version = ord($version); if ($version !== $this->options["version"]) { $message = sprintf( 'Version "%s" does not match the expected "%s"', $version, $this->options["version"] ); throw new RuntimeException($message); } $decoded = substr($decoded, Base58::VERSION_SIZE, -(Base58::CHECKSUM_SIZE)); } return $decoded; }
Decode given base58 string back to data
entailment
public function getArray() { $parsed = @simplexml_load_file($this->context); if (! $parsed) { throw new InvalidFileException('Unable to parse invalid XML file at ' . $this->context); } return json_decode(json_encode($parsed), true); }
Retrieve the contents of a .json file and convert it to an array of configuration options. @return array Array of configuration options
entailment
public function set($key, $value) { $config = &$this->config; foreach (explode('.', $key) as $k) { $config = &$config[$k]; } $config = $value; return true; }
Store a config value with a specified key. @param string $key Unique configuration option key @param mixed $value Config item value @return bool True on success, otherwise false
entailment
public function get($key, $default = null) { $config = $this->config; foreach (explode('.', $key) as $k) { if (! isset($config[$k])) { return $default; } $config = $config[$k]; } return $config; }
Retrieve a configuration option via a provided key. @param string $key Unique configuration option key @param mixed $default Default value to return if option does not exist @return mixed Stored config item or $default value
entailment
public function has($key) { $config = $this->config; foreach (explode('.', $key) as $k) { if (! isset($config[$k])) { return false; } $config = $config[$k]; } return true; }
Check for the existence of a configuration item. @param string $key Unique configuration option key @return bool True if item existst, otherwise false
entailment
public function load($path, $prefix = null, $override = true) { $file = new SplFileInfo($path); $className = $file->isDir() ? 'Directory' : ucfirst(strtolower($file->getExtension())); $classPath = 'PHLAK\\Config\\Loaders\\' . $className; $loader = new $classPath($file->getRealPath()); $newConfig = $prefix ? [$prefix => $loader->getArray()] : $loader->getArray(); if ($override) { $this->config = array_replace_recursive($this->config, $newConfig); } else { $this->config = array_replace_recursive($newConfig, $this->config); } return $this; }
Load configuration options from a file or directory. @param string $path Path to configuration file or directory @param string $prefix A key under which the loaded config will be nested @param bool $override Whether or not to override existing options with values from the loaded file @return self This Config object
entailment
public function merge(self $config, $override = true) { if ($override) { $this->config = array_replace_recursive($this->config, $config->toArray()); } else { $this->config = array_replace_recursive($config->toArray(), $this->config); } return $this; }
Merge another Config object into this one. @param Config $config Instance of Config @param bool $override Whether or not to override existing options with values from the merged config object @return self This Config object
entailment
public function getArray() { $contents = []; foreach (new DirectoryIterator($this->context) as $file) { if ($file->isDot()) { continue; } $className = $file->isDir() ? 'Directory' : ucfirst(strtolower($file->getExtension())); $classPath = 'PHLAK\\Config\\Loaders\\' . $className; $loader = new $classPath($file->getPathname()); try { $contents = array_merge($contents, $loader->getArray()); } catch (InvalidFileException $e) { // Ignore it and continue } } return $contents; }
Retrieve the contents of one or more configuration files in a directory and convert them to an array of configuration options. Any invalid files will be silently ignored. @return array Array of configuration options
entailment
public function getArray() { $contents = file_get_contents($this->context); $parsed = json_decode($contents, true); if (is_null($parsed)) { throw new InvalidFileException('Unable to parse invalid JSON file at ' . $this->context); } return $parsed; }
Retrieve the contents of a .json file and convert it to an array of configuration options. @return array Array of configuration options
entailment
public static function getKeyUri($type, $label, $secret, $counter = null, $options = array()) { // two types only.. if (!in_array($type, self::$allowedTypes)) { throw new \InvalidArgumentException('Type has to be of allowed types list'); } // Label can't be empty $label = trim($label); if (strlen($label) < 1) { throw new \InvalidArgumentException('Label has to be one or more printable characters'); } if (substr_count($label, ':') > 2) { throw new \InvalidArgumentException('Account name contains illegal colon characters'); } // Secret needs to be here if (strlen($secret) < 1) { throw new \InvalidArgumentException('No secret present'); } // check for counter on hotp if ($type == 'hotp' && is_null($counter)) { throw new \InvalidArgumentException('Counter required for hotp'); } // This is the base, these are at least required $otpauth = 'otpauth://' . $type . '/' . rawurlencode($label) . '?secret=' . rawurlencode($secret); if ($type == 'hotp' && !is_null($counter)) { $otpauth .= '&counter=' . intval($counter); } // Now check the options array // algorithm (currently ignored by Authenticator) // Defaults to SHA1 if (array_key_exists('algorithm', $options)) { $otpauth .= '&algorithm=' . rawurlencode($options['algorithm']); } // digits (currently ignored by Authenticator) // Defaults to 6 if (array_key_exists('digits', $options) && intval($options['digits']) !== 6 && intval($options['digits']) !== 8) { throw new \InvalidArgumentException('Digits can only have the values 6 or 8, ' . $options['digits'] . ' given'); } elseif (array_key_exists('digits', $options)) { $otpauth .= '&digits=' . intval($options['digits']); } // period, only for totp (currently ignored by Authenticator) // Defaults to 30 if ($type == 'totp' && array_key_exists('period', $options)) { $otpauth .= '&period=' . rawurlencode($options['period']); } // issuer // Defaults to none if (array_key_exists('issuer', $options)) { $otpauth .= '&issuer=' . rawurlencode($options['issuer']); } // image (to accepts images for freeotp) if (array_key_exists('image', $options)) { $otpauth .= '&image=' . $options['image']; } return $otpauth; }
Returns the Key URI Format of encoded url is here: https://code.google.com/p/google-authenticator/wiki/KeyUriFormat Should be done in a better fashion @param string $type totp or hotp @param string $label Label to display this as to the user @param string $secret Base32 encoded secret @param integer $counter Required by hotp, otherwise ignored @param array $options Optional fields that will be set if present @return string Key URI
entailment
public static function getQrCodeUrl($type, $label, $secret, $counter = null, $options = array()) { // Width and height can be overwritten $width = self::$width; if (array_key_exists('width', $options) && is_numeric($options['width'])) { $width = $options['width']; } $height = self::$height; if (array_key_exists('height', $options) && is_numeric($options['height'])) { $height = $options['height']; } $otpauth = self::getKeyUri($type, $label, $secret, $counter, $options); $url = 'https://chart.googleapis.com/chart?chs=' . $width . 'x' . $height . '&cht=qr&chld=M|0&chl=' . urlencode($otpauth); return $url; }
Returns the QR code url Format of encoded url is here: https://code.google.com/p/google-authenticator/wiki/KeyUriFormat Should be done in a better fashion @param string $type totp or hotp @param string $label Label to display this as to the user @param string $secret Base32 encoded secret @param integer $counter Required by hotp, otherwise ignored @param array $options Optional fields that will be set if present @return string URL to the QR code
entailment
public static function generateRandom($length = 16) { $keys = array_merge(range('A','Z'), range(2,7)); // No padding char $string = ''; for ($i = 0; $i < $length; $i++) { $string .= $keys[random_int(0, 31)]; } return $string; }
Creates a pseudo random Base32 string This could decode into anything. It's located here as a small helper where code that might need base32 usually also needs something like this. @param integer $length Exact length of output string @return string Base32 encoded random
entailment
public static function generateRecoveryCodes($count = 1, $length = 9) { $count = intval($count); $length = intval($length); $codes = []; do { // Generate codes $code = ''; for ($i = 1; $i <= $length; $i++) { $code .= random_int(0, 9); } // To make sure no duplicates get in if (!in_array($code, $codes)) { $codes[] = $code; } } while (count($codes) < $count); return $codes; }
Create recovery codes A pure helper function to make your life easier. Generates a list of codes, guaranteed to be unique in the set @param integer $count How many codes to return @param integer $length How long each code should be @return array Array of codes
entailment
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $treeBuilder ->root('nilportugues_json_api') ->children() ->arrayNode('mappings') ->prototype('scalar') ->isRequired() ->cannotBeEmpty() ->end() ->end() ->scalarNode('attributes_case') ->defaultValue('snake_case') ->validate() ->ifNotInArray(['snake_case', 'keep_case']) // @TODO: implement forcing camelCase and hypen-case. ->thenInvalid('Invalid case setting %s, valid values are: snake_case, keep_case') ->end() ->end(); return $treeBuilder; }
{@inheritdoc}
entailment
public function getArray() { try { $parsed = YamlParser::parse(file_get_contents($this->context)); } catch (ParseException $e) { throw new InvalidFileException($e->getMessage()); } if (! is_array($parsed)) { throw new InvalidFileException('Unable to parse invalid YAML file at ' . $this->context); } return $parsed; }
Retrieve the contents of a .yaml file and convert it to an array of configuration options. @return array Array of configuration options
entailment
protected function errorResponse($json) { $error = new Error('Bad Request', json_decode($json)); return $this->createResponse(new BadRequest(new ErrorBag([$error]))); }
@param string $json @return \Symfony\Component\HttpFoundation\Response
entailment
protected function resourceNotFoundResponse($json) { $error = new Error('Resource not Found', json_decode($json)); return $this->createResponse(new ResourceNotFound(new ErrorBag([$error]))); }
@param string $json @return \Symfony\Component\HttpFoundation\Response
entailment
protected function resourcePatchErrorResponse($json) { $error = new Error('Unprocessable Entity', json_decode($json)); return $this->createResponse(new UnprocessableEntity([$error])); }
@param string $json @return \Symfony\Component\HttpFoundation\Response
entailment
protected function resourcePostErrorResponse($json) { $error = new Error('Unprocessable Entity', json_decode($json)); return $this->createResponse(new UnprocessableEntity([$error])); }
@param string $json @return \Symfony\Component\HttpFoundation\Response
entailment
protected function unsupportedActionResponse($json) { $error = new Error('Unsupported Action', json_decode($json)); return $this->createResponse(new UnsupportedAction([$error])); }
@param string $json @return \Symfony\Component\HttpFoundation\Response
entailment
public function hotp($secret, $counter) { if (!is_numeric($counter) || $counter < 0) { throw new \InvalidArgumentException('Invalid counter supplied'); } $hash = hash_hmac( $this->algorithm, $this->getBinaryCounter($counter), $secret, true ); return str_pad($this->truncate($hash), $this->digits, '0', STR_PAD_LEFT); }
/* (non-PHPdoc) @see Otp.OtpInterface::hotp()
entailment