code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
public function getDynamicUriString()
{
$stack = new StackUri('dynamic', $this->getStackOperations(), $this->getStackOptions(), $this->getStackVariables());
return $stack->getStackUriString();
} | Returns the stack url part as a dynamic stack for previewing.
@since 1.2.0
@throws \RuntimeException When the stack name could not be parsed correctly
@return string |
public static function createFromJsonResponse($data)
{
$data = json_decode($data, true);
$stacks = array_map(function ($stack) {
return Stack::createFromDecodedJsonResponse($stack);
}, $data['items']);
return new self($stacks);
} | Create a stack from the JSON data returned by the rokka.io API.
@param string $data JSON data
@return StackCollection |
public static function keyExpansion($key) { // generate Key Schedule from Cipher Key [§5.2]
$Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES)
$Nk = count($key)/4; // key length (in words): 4/6/8 for 128/192/256-bit keys
$Nr = $Nk + 6; // no of rounds: 10/12/14 for 128/192/256-bit keys
$w = array();
$temp = array();
for ($i=0; $i<$Nk; $i++) {
$r = array($key[4*$i], $key[4*$i+1], $key[4*$i+2], $key[4*$i+3]);
$w[$i] = $r;
}
for ($i=$Nk; $i<($Nb*($Nr+1)); $i++) {
$w[$i] = array();
for ($t=0; $t<4; $t++) $temp[$t] = $w[$i-1][$t];
if ($i % $Nk == 0) {
$temp = self::subWord(self::rotWord($temp));
for ($t=0; $t<4; $t++) $temp[$t] ^= self::$rCon[$i/$Nk][$t];
} else if ($Nk > 6 && $i%$Nk == 4) {
$temp = self::subWord($temp);
}
for ($t=0; $t<4; $t++) $w[$i][$t] = $w[$i-$Nk][$t] ^ $temp[$t];
}
return $w;
} | Key expansion for Rijndael cipher(): performs key expansion on cipher key
to generate a key schedule
@param key cipher key byte-array (16 bytes)
@return array key schedule as 2D byte-array (Nr+1 x Nb bytes) |
public function click($time=null) {
$this->total++;
if ( ! $this->timestart ) {
$this->timestart = (int) ( time() / $this->scale );
}
if ( ! $time ) $time = time();
$time = (int) ($time / $this->scale);
$delta = $time - $this->timestart;
if ( $delta < 0 ) $delta = 0; // 0 is OK
if ( isset($this->buckets[$delta]) ) {
$this->buckets[$delta]++;
} else {
$this->buckets[$delta] = 1;
}
} | Record a click... |
public function reconstruct() {
$retval = array();
foreach($this->buckets as $k => $v) {
$t = ($this->timestart + $k) * $this->scale;
$retval[$t] = $v;
}
return $retval;
} | Reconstruct to the actual times |
public function viewModel() {
$retval = new \stdClass();
$buckets = $this->reconstruct();
$retval->timestart = $this->timestart * $this->scale;
$retval->width = $this->scale;
$max = false;
$maxt = false;
$min = false;
$rows = array();
foreach($buckets as $k => $v ) {
if ( $maxt === false || $k > $maxt ) $maxt = $k;
if ( $max === false || $v > $max ) $max = $v;
if ( $min === false || $v < $min ) $min = $v;
$rows[] = array($k,$v);
}
$retval->rows = $rows;
$retval->n = count($rows);
$retval->max = $max;
$retval->min = $min;
$retval->timeend = $maxt;
return $retval;
} | Produce an view model of the entire object
This is a "view model" in that it is intended to be easily used
in rendering situations. |
public function reScale($factor=2) {
$newbuckets = array();
$newscale = $this->scale * $factor;
$newstart = (int) ($this->timestart / $factor);
foreach($this->buckets as $k => $v) {
$oldtime = ($this->timestart + $k) * $this->scale;
$newposition = (int) ($oldtime / $newscale);
$delta = $newposition - $newstart;
if ( isset($newbuckets[$delta]) ) {
$newbuckets[$delta] += $v;
} else {
$newbuckets[$delta] = $v;
}
}
return $newbuckets;
} | Double the Scale - Return *copy of* new buckets |
public static function uncompressEntry($text) {
if ( $text === null | $text === false ) return $text;
$needed = false;
for ($i = 0; $i < strlen($text); $i++){
$ch = $text[$i];
if ( $ch >= '0' && $ch <= '9' ) continue;
if ( $ch == ':' || $ch == ',' || $ch == '=' ) continue;
$needed = true;
break;
}
if ( ! $needed ) return $text;
return gzuncompress($text);
} | Optionally uncompress a serialized entry if it is compressed |
public function deSerialize($data) {
$data = self::uncompressEntry($data);
$chunks = explode(':',$data);
// Nothing to see here - Might be null ... is OK
if ( count($chunks) != 3 || !is_numeric($chunks[0]) || !is_numeric($chunks[1]) ) {
$this->scale = 900;
$this->timestart = 0;
$this->buckets = array();
return;
}
$this->scale = (int) $chunks[0];
$this->timestart = (int) $chunks[1];
$this->buckets = U::array_Integer_Deserialize($chunks[2]);
} | De-Serialize scale, timestart and buckets (can be compressed)
Does not set total |
public static function createFromJsonResponse($jsonString)
{
$data = json_decode($jsonString, true);
$sourceImages = array_map(function ($sourceImage) {
return SourceImage::createFromDecodedJsonResponse($sourceImage);
}, $data['items']);
$total = isset($data['total']) ? $data['total'] : 0;
$links = isset($data['links']) ? $data['links'] : [];
$cursor = isset($data['cursor']) ? $data['cursor'] : null;
return new self($sourceImages, $total, $links, $cursor);
} | Create a collection from the JSON data returned by the rokka.io API.
@param string $jsonString JSON as a string
@return SourceImageCollection |
function getLoginUrl($state) {
$loginUrl = "https://accounts.google.com/o/oauth2/auth?"
. "client_id=" . $this->client_id
. "&redirect_uri=" . $this->redirect
. "&state=" . $state
. "&response_type=code"
. "&scope=email%20profile"
. "&include_granted_scopes=true";
if ( $this->openid_realm ) {
$loginUrl .= "&openid.realm=" . $this->openid_realm;
}
return $loginUrl;
} | Get the login url |
function getAccessToken($google_code) {
// Make sure these are clear if we fail
$this->authentication_object = FALSE;
$this->access_token = FALSE;
// From: https://github.com/PenguinProtocols/Basic-OpenID-Connect-Google
// This approach gets us the openid_id from the former realm
$token_url = "https://www.googleapis.com/oauth2/v3/token";
$post = "code={$google_code}&client_id={$this->client_id}&client_secret={$this->client_secret}"
. "&redirect_uri={$this->redirect}&grant_type=authorization_code";
if ( $this->openid_realm ) {
$post .= "&openid.realm=" . $this->openid_realm;
}
$response = $this->curl_post($token_url, $post);
/* $response normally looks like this:
{
"access_token" : "QEX3L0Fm ... about 80 characters ... 4tLMYze617",
"token_type" : "Bearer",
"expires_in" : 3599,
"id_token" : "hbGciO ... about 700 characers ... t3cE"
}
*/
if ($response) {
$this->authentication_object = json_decode($response);
}
if (isset($this->authentication_object->refresh_token)) {
$this->Google_RefreshToken = $this->authentication_object->refresh_token;
}
if (isset($this->authentication_object->access_token)) {
$this->access_token = $this->authentication_object->access_token;
return $this->authentication_object;
} else {
return FALSE;
}
} | Get the access token |
function getUserInfo($access_token=FALSE) {
if ( $access_token === FALSE ) $access_token = $this->access_token;
if ( $access_token === FALSE ) return FALSE;
$user_info_url = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" .
$access_token;
$response = $this->curl_get($user_info_url);
/* $response looks like this:
{
"id": "105526282828383882908",
"email": "dr.chuck@gmail.com",
"verified_email": true,
"name": "Chuck Severance",
"given_name": "Chuck",
"family_name": "Severance",
"link": "https://plus.google.com/+ChuckSeverance",
"picture": "https://lh4.googleusercontent.com/sWWd ... Fr9lw/photo.jpg",
"gender": "male",
"locale": "en"
}
*/
$user = json_decode($response);
if ( ! $user ) return FALSE;
// Get the old openid_id if we asked for and received it
$user->openid_id = false;
if ( $this->authentication_object && isset($this->authentication_object->id_token) ) {
$id_token = $this->authentication_object->id_token;
$info = JWT::decode($id_token, $this->client_secret, false);
if ( $info && isset($info->sub) && isset($info->openid_id) ) {
$user->openid_id = $info->openid_id;
}
}
return $user;
} | /*
Retieve the profile information |
function curl_post($url, $post) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$json_response = curl_exec($curl);
$this->last_response = $json_response;
curl_close($curl);
return $json_response;
} | Utility code in order not to have external dependencies
and to have some logging. |
function curl_get($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
$json_response = curl_exec($curl);
$this->last_response = $json_response;
curl_close($curl);
return $json_response;
} | Utility code in order not to have external dependencies
and to have some logging. |
public function parse_mime_type($mime_type) {
$parts = explode(";", $mime_type);
$params = array();
foreach ($parts as $i=>$param) {
if (strpos($param, '=') !== false) {
list ($k, $v) = explode('=', trim($param));
$params[$k] = $v;
}
}
$full_type = trim($parts[0]);
/* Java URLConnection class sends an Accept header that includes a single "*"
Turn it into a legal wildcard. */
if ($full_type == '*') {
$full_type = '*/*';
}
if ( trim($full_type) == '' ) {
error_log("mime type is blank");
$full_type = '*/*';
}
$pieces = explode('/', $full_type);
if ( count($pieces) < 2 ) {
error_log("malformed mime type ".$full_type);
throw (new \Exception("malformed mime type ".$full_type));
}
list ($type, $subtype) = $pieces;
return array(trim($type), trim($subtype), $params);
} | Carves up a mime-type and returns an Array of the [type, subtype, params]
where "params" is a Hash of all the parameters for the media range.
For example, the media range "application/xhtml;q=0.5" would
get parsed into:
array("application", "xhtml", array( "q" => "0.5" ))
@param string $mime_type
@return array ($type, $subtype, $params) |
public function parse_media_range($range) {
list ($type, $subtype, $params) = $this->parse_mime_type($range);
if (!(isset($params['q']) && $params['q'] && floatval($params['q']) &&
floatval($params['q']) <= 1 && floatval($params['q']) >= 0))
$params['q'] = '1';
return array($type, $subtype, $params);
} | Carves up a media range and returns an Array of the
[type, subtype, params] where "params" is a Hash of all
the parameters for the media range.
For example, the media range "application/*;q=0.5" would
get parsed into:
array("application", "*", ( "q", "0.5" ))
In addition this function also guarantees that there
is a value for "q" in the params dictionary, filling it
in with a proper default if necessary.
@param string $range
@return array ($type, $subtype, $params) |
public function fitness_and_quality_parsed($mime_type, $parsed_ranges) {
$best_fitness = -1;
$best_fit_q = 0;
list ($target_type, $target_subtype, $target_params) = $this->parse_media_range($mime_type);
foreach ($parsed_ranges as $item) {
list ($type, $subtype, $params) = $item;
if (($type == $target_type or $type == "*" or $target_type == "*") &&
($subtype == $target_subtype or $subtype == "*" or $target_subtype == "*")) {
$param_matches = 0;
foreach ($target_params as $k=>$v) {
if ($k != 'q' && isset($params[$k]) && $v == $params[$k])
$param_matches++;
}
$fitness = ($type == $target_type) ? 100 : 0;
$fitness += ($subtype == $target_subtype) ? 10 : 0;
$fitness += $param_matches;
if ($fitness > $best_fitness) {
$best_fitness = $fitness;
$best_fit_q = $params['q'];
}
}
}
return array( $best_fitness, (float) $best_fit_q );
} | Find the best match for a given mime-type against a list of
media_ranges that have already been parsed by Mimeparser::parse_media_range()
Returns the fitness and the "q" quality parameter of the best match, or an
array [-1, 0] if no match was found. Just as for Mimeparser::quality(),
"parsed_ranges" must be an Enumerable of parsed media ranges.
@param string $mime_type
@param array $parsed_ranges
@return array ($best_fitness, $best_fit_q) |
public function quality_parsed($mime_type, $parsed_ranges) {
list ($fitness, $q) = $this->fitness_and_quality_parsed($mime_type, $parsed_ranges);
return $q;
} | Find the best match for a given mime-type against a list of
media_ranges that have already been parsed by Mimeparser::parse_media_range()
Returns the "q" quality parameter of the best match, 0 if no match
was found. This function behaves the same as Mimeparser::quality() except that
"parsed_ranges" must be an Enumerable of parsed media ranges.
@param string $mime_type
@param array $parsed_ranges
@return float $q |
public function quality($mime_type, $ranges) {
$parsed_ranges = explode(',', $ranges);
foreach ($parsed_ranges as $i=>$r)
$parsed_ranges[ $i ] = $this->parse_media_range($r);
return $this->quality_parsed($mime_type, $parsed_ranges);
} | Returns the quality "q" of a mime-type when compared against
the media-ranges in ranges. For example:
Mimeparser::quality("text/html", "text/*;q=0.3, text/html;q=0.7,
text/html;level=1, text/html;level=2;q=0.4, *\/*;q=0.5")
=> 0.7
@param unknown_type $mime_type
@param unknown_type $ranges
@return unknown |
public function best_match($supported, $header) {
$parsed_header = $header;
if ( is_string($header) ) {
$parsed_header = explode(',', $header);
}
foreach ($parsed_header as $i=>$r)
$parsed_header[ $i ] = $this->parse_media_range($r);
$weighted_matches = array();
foreach ($supported as $mime_type) {
$weighted_matches[] = array(
$this->fitness_and_quality_parsed($mime_type, $parsed_header),
$mime_type
);
}
array_multisort($weighted_matches);
$a = $weighted_matches[ count($weighted_matches) - 1 ];
return ( empty( $a[0][1] ) ? null : $a[1] );
} | Takes a list of supported mime-types and finds the best match
for all the media-ranges listed in header. The value of header
must be a string that conforms to the format of the HTTP Accept:
header. The value of supported is an Enumerable of mime-types
Mimeparser::best_match(array("application/xbel+xml", "text/xml"), "text/*;q=0.5,*\/*; q=0.1")
=> "text/xml"
@param array $supported
@param string $header
@return mixed $mime_type or NULL |
public static function get($arr, $key, $default=null) {
if ( !is_array($arr) ) return $default;
if ( !isset($key) ) return $default;
if ( !isset($arr[$key]) ) return $default;
return $arr[$key];
} | Produce a Python-style get() to avoid use of ternary operator |
public static function route_get_local_path($dir) {
$uri = $_SERVER['REQUEST_URI']; // /tsugi/lti/some/cool/stuff
$root = $_SERVER['DOCUMENT_ROOT']; // /Applications/MAMP/htdocs
$cwd = $dir; // /Applications/MAMP/htdocs/tsugi/lti
if ( strlen($cwd) < strlen($root) + 1 ) return false;
$lwd = substr($cwd,strlen($root)); // /tsugi/lti
if ( strlen($uri) < strlen($lwd) + 2 ) return false;
$local = substr($uri,strlen($lwd)+1); // some/cool/stuff
return $local;
} | Convienence method to get the local path if we are doing |
public static function get_request_document() {
$uri = $_SERVER['REQUEST_URI']; // /tsugi/lti/some/cool/stuff
$pieces = explode('/',$uri);
if ( count($pieces) > 1 ) {
$local_path = $pieces[count($pieces)-1];
$pos = strpos($local_path,'?');
if ( $pos > 0 ) $local_path = substr($local_path,0,$pos);
return $local_path;
}
return false;
} | Get the last bit of the path
input: /py4e/lessons/intro?x=2
output: intro |
public static function get_base_url($url) {
$pieces = parse_url($url);
$retval = $pieces['scheme'].'://'.$pieces['host'];
$port = self::get($pieces,'port');
if ( $port && $port != 80 && $port != 443 ) $retval .= ':' . $port;
return $retval;
} | Get the protocol, host, and port from an absolute URL
input: http://localhost:8888/tsugi
output: http://localhost:8888 |
public static function get_rest_path($uri=false) {
if ( ! $uri ) $uri = $_SERVER['REQUEST_URI']; // /tsugi/lti/some/cool/stuff
$pos = strpos($uri,'?');
if ( $pos > 0 ) $uri = substr($uri,0,$pos);
if ( self::endsWith($uri, '/') ) {
$uri = substr($uri, 0, strlen($uri)-1);
}
return $uri;
} | Get the path to the current request, w/o trailing slash
input: /py4e/lessons/intro?x=2
output: /py4e/lessons/intro
input: /py4e/lessons/intro/?x=2
output: /py4e/lessons/intro |
public static function get_rest_parent($uri=false) {
if ( ! $uri ) $uri = $_SERVER['REQUEST_URI']; // /tsugi/lti/some/cool/stuff
$pos = strpos($uri,'?');
if ( $pos > 0 ) $uri = substr($uri,0,$pos);
if ( self::endsWith($uri, '/') ) {
$uri = substr($uri, 0, strlen($uri)-1);
return $uri;
}
$pieces = explode('/', $uri);
if ( count($pieces) > 1 ) {
array_pop($pieces);
$uri = implode('/', $pieces);
}
return $uri;
} | Get the path to one above the current request, w/o trailing slash
input: /py4e/lessons/intro?x=2
output: /py4e/lessons
input: /py4e/lessons/intro/?x=2
output: /py4e/lessons/intro |
public static function parse_rest_path($uri=false, $SERVER_SCRIPT_NAME=false /* unit test only */) {
if ( ! $SERVER_SCRIPT_NAME ) $SERVER_SCRIPT_NAME = $_SERVER["SCRIPT_NAME"]; // /py4e/koseu.php
if ( ! $uri ) $uri = $_SERVER['REQUEST_URI']; // /py4e/lessons/intro/happy
// Remove Query string...
$pos = strpos($uri, '?');
if ( $pos !== false ) $uri = substr($uri,0,$pos);
$cwd = dirname($SERVER_SCRIPT_NAME);
if ( strpos($uri,$cwd) !== 0 ) return false;
$controller = '';
$extra = '';
$remainder = substr($uri, strlen($cwd));
if ( strpos($remainder,'/') === 0 ) $remainder = substr($remainder,1);
if ( strlen($remainder) > 1 ) {
$pieces = explode('/',$remainder,2);
if ( count($pieces) > 0 ) $controller = $pieces[0];
if ( count($pieces) > 1 ) $extra = $pieces[1];
}
if ( $cwd == '/' ) $cwd = '';
$retval = array($cwd, $controller, $extra);
return $retval;
} | Get the controller for the current request
executing script: /py4e/koseu.php
input: /py4e/lessons/intro?x=2
output: (/py4e, lessons, intro)
input: /py4e/lessons/intro/?x=2
output: /py4e/lessons/intro |
public static function remove_relative_path($path) {
$pieces = explode('/', $path);
$new_pieces = array();
for($i=0; $i < count($pieces); $i++) {
if ($pieces[$i] == '.' ) continue;
if ($pieces[$i] == '..' ) {
array_pop($new_pieces);
continue;
}
$new_pieces[] = $pieces[$i];
}
$retval = implode("/",$new_pieces);
return $retval;
} | Remove any relative elements from a path
Before After
a/b/c a/b/c
a/b/c/ a/b/c/
a/./c/ a/c/
a/../c/ c/ |
public static function http_response_code($newcode = NULL)
{
static $code = 200;
if($newcode !== NULL)
{
header('X-PHP-Response-Code: '.$newcode, true, $newcode);
if(!headers_sent())
$code = $newcode;
}
return $code;
} | For 4.3.0 <= PHP <= 5.4.0 |
public static function curPHPUrl() {
$scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
? 'http'
: 'https';
$port = "";
if ( isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != "80" && $_SERVER['SERVER_PORT'] != "443" &&
strpos(':', $_SERVER['HTTP_HOST']) < 0 ) {
$port = ':' . $_SERVER['SERVER_PORT'] ;
}
$http_url = $scheme .
'://' . $_SERVER['HTTP_HOST'] .
$port .
$_SERVER['REQUEST_URI'];
return $http_url;
} | Return the URL as seen by PHP (no query string or parameters)
Borrowed from from_request on OAuthRequest.php |
public static function array_Integer_Deserialize($input) {
$r = array();
preg_match_all("/([^,= ]+)=([^,= ]+)/", $input, $r);
$result = array();
for($i=0; $i<count($r[1]);$i++) {
$k = $r[1][$i];
$v = $r[2][$i];
if ( !is_numeric($k) || !is_numeric($v) ) {
throw new \Exception('array_Integer_Deserialize requires integers '.$k.'='.$v.' ('.$i.')');
}
$k = $k + 0;
$v = $v + 0;
if ( ! is_int($k) || ! is_int($v) ) {
throw new \Exception('array_Integer_Deserialize requires integers '.$k.'='.$v.' ('.$i.')');
}
$result[$k] = $v;
}
return $result;
} | Deserialize an tightly serialized integer-only PHP array
$str = '1=42,2=43,3=44';
$arar = U::array_Integer_Deserialize($str);
print_r($arar); // Array ( '1' => 42 ,'2' => 43, '3' => 44 );
https://stackoverflow.com/questions/4923951/php-split-string-in-key-value-pairs |
public static function array_kshift(&$arr) {
list($k) = array_keys($arr);
$r = array($k=>$arr[$k]);
unset($arr[$k]);
return $r;
} | Pull off the first element of a key/value array
$arr = array('x'=>'ball','y'=>'hat','z'=>'apple');
print_r($arr);
print_r(array_kshift($arr)); // [x] => ball
print_r($arr);
http://php.net/manual/en/function.array-shift.php#84179 |
public static function allow_track() {
$DoNotTrackHeader = "DNT";
$DoNotTrackValue = "1";
$phpHeader = "HTTP_" . strtoupper(str_replace("-", "_", $DoNotTrackHeader));
$retval = ! ((array_key_exists($phpHeader, $_SERVER)) and ($_SERVER[$phpHeader] == $DoNotTrackValue));
return $retval;
} | From: http://donottrack.us/application |
public static function safe_var_dump($x) {
ob_start();
if ( isset($x['secret']) ) $x['secret'] = MD5($x['secret']);
if ( is_array($x) ) foreach ( $x as &$v ) {
if ( is_array($v) && isset($v['secret']) ) $v['secret'] = MD5($v['secret']);
}
var_dump($x);
$result = ob_get_clean();
return $result;
} | Clean out the array of 'secret' keys |
public static function getCaller($count=1)
{
$dbts=debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS,6+$count);
if ( ! is_array($dbts) || count($dbts) < 2 ) return null;
if ( ! isset($dbts[0]['file']) ) return null;
$myfile = $dbts[0]['file'];
$retval = '';
foreach($dbts as $dbt) {
if ( ! isset($dbt['file']) ) continue;
if ( ! isset($dbt['line']) ) continue;
if ( $myfile != $dbt['file'] ) {
if ( strlen($retval) > 0 ) $retval .= " ";
$retval.= $dbt['file'].':'.$dbt['line'];
$count--;
if ( $count < 1 ) return $retval;
}
}
return $retval;
} | Need to replicate the code or U.php will be in the traceback |
public function invoke(AbstractRequest $request)
{
$this->invoker->invoke($request);
$current = clone $request->resourceObject;
foreach ($request->links as $link) {
/* @noinspection ExceptionsAnnotatingAndHandlingInspection */
$nextResource = $this->annotationLink($link, $current, $request);
$current = $this->nextLink($link, $current, $nextResource);
}
return $current;
} | {@inheritdoc}
@throws LinkQueryException
@throws \BEAR\Resource\Exception\LinkRelException |
private function nextLink(LinkType $link, ResourceObject $ro, $nextResource) : ResourceObject
{
$nextBody = $nextResource instanceof ResourceObject ? $nextResource->body : $nextResource;
if ($link->type === LinkType::SELF_LINK) {
$ro->body = $nextBody;
return $ro;
}
if ($link->type === LinkType::NEW_LINK) {
$ro->body[$link->key] = $nextBody;
return $ro;
}
// crawl
return $ro;
} | How next linked resource treated (add ? replace ?) |
private function annotationLink(LinkType $link, ResourceObject $current, AbstractRequest $request)
{
if (! is_array($current->body)) {
throw new Exception\LinkQueryException('Only array is allowed for link in ' . get_class($current), 500);
}
$classMethod = 'on' . ucfirst($request->method);
$annotations = $this->reader->getMethodAnnotations(new \ReflectionMethod(get_class($current), $classMethod));
if ($link->type === LinkType::CRAWL_LINK) {
return $this->annotationCrawl($annotations, $link, $current);
}
/* @noinspection ExceptionsAnnotatingAndHandlingInspection */
return $this->annotationRel($annotations, $link, $current)->body;
} | Annotation link
@throws \BEAR\Resource\Exception\MethodException
@throws \BEAR\Resource\Exception\LinkRelException
@throws Exception\LinkQueryException
@return mixed|ResourceObject |
private function annotationRel(array $annotations, LinkType $link, ResourceObject $current) : ResourceObject
{
/* @noinspection LoopWhichDoesNotLoopInspection */
foreach ($annotations as $annotation) {
if ($annotation->rel !== $link->key) {
continue;
}
$uri = uri_template($annotation->href, $current->body);
$rel = $this->factory->newInstance($uri);
/* @noinspection UnnecessaryParenthesesInspection */
$request = new Request($this->invoker, $rel, Request::GET, (new Uri($uri))->query);
return $this->invoker->invoke($request);
}
throw new LinkRelException("rel:{$link->key} class:" . get_class($current), 500);
} | Annotation link (new, self)
@param \BEAR\Resource\Annotation\Link[] $annotations
@throws \BEAR\Resource\Exception\UriException
@throws \BEAR\Resource\Exception\MethodException
@throws Exception\LinkQueryException
@throws Exception\LinkRelException |
private function annotationCrawl(array $annotations, LinkType $link, ResourceObject $current) : ResourceObject
{
$isList = $this->isList($current->body);
$bodyList = $isList ? (array) $current->body : [$current->body];
foreach ($bodyList as &$body) {
/* @noinspection ExceptionsAnnotatingAndHandlingInspection */
$this->crawl($annotations, $link, $body);
}
unset($body);
$current->body = $isList ? $bodyList : $bodyList[0];
return $current;
} | Link annotation crawl
@throws \BEAR\Resource\Exception\MethodException |
public function getParameters(callable $callable, array $query) : array
{
$metas = ($this->paramMetas)($callable);
$parameters = [];
foreach ($metas as $varName => $param) {
/* @var $param ParamInterface */
$parameters[] = $param($varName, $query, $this->injector);
}
return $parameters;
} | {@inheritdoc} |
public function getStackOperationsByName($name)
{
$stackOperations = [];
foreach ($this->stackOperations as $stackOperation) {
if ($stackOperation->name === $name) {
$stackOperations[] = $stackOperation;
}
}
return $stackOperations;
} | Returns all operations matching name.
@since 1.2.0
@param string $name operation name
@return StackOperation[] |
public function setStackOperations(array $operations)
{
$this->stackOperations = [];
foreach ($operations as $operation) {
$this->addStackOperation($operation);
}
return $this;
} | @since 1.1.0
@param StackOperation[] $operations
@return self |
public function setResult($var)
{
GPBUtil::checkEnum($var, \Rxnet\EventStore\Data\OperationResult::class);
$this->result = $var;
return $this;
} | Generated from protobuf field <code>.Rxnet.EventStore.Data.OperationResult result = 2;</code>
@param int $var
@return $this |
public static function get_headers_internal() {
if (function_exists('apache_request_headers')) {
// we need this to get the actual Authorization: header
// because apache tends to tell us it doesn't exist
return apache_request_headers();
}
// otherwise we don't have apache and are just going to have to hope
// that $_SERVER actually contains what we need
$out = array();
foreach ($_SERVER as $key => $value) {
if (substr($key, 0, 5) == "HTTP_") {
// this is chaos, basically it is just there to capitalize the first
// letter of every word that is not an initial HTTP and strip HTTP
// code from przemek
$key = str_replace(
" ",
"-",
ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
);
$out[$key] = $value;
}
}
return $out;
} | helper to try to sort out headers for people who aren't running apache |
public static function get_headers() {
$headers = OAuthUtil::get_headers_internal();
if ( ! is_array($headers) ) return $headers;
if ( (! isset($headers['Authorization'])) && isset($headers['X-Oauth1-Authorization']) ) {
$headers['Authorization'] = $headers['X-Oauth1-Authorization'];
}
return $headers;
} | header on our behalf - fall back to the alternate Authorization header. |
public static function createFromArray($config)
{
if (!isset($config['stack'])) {
throw new \RuntimeException('Stack has to be set');
}
$hash = isset($config['hash']) ? $config['hash'] : null;
$format = isset($config['format']) ? $config['format'] : null;
$filename = isset($config['filename']) ? $config['filename'] : null;
return new self($config['stack'], $hash, $format, $filename);
} | Creates a UriComponent object from an array with 'stack', 'hash', 'format', 'filename' and 'stack' as keys.
@since 1.2.0
@param mixed $config |
public function setStack($stack)
{
if ($stack instanceof StackUri) {
$this->stack = $stack;
} elseif (\is_string($stack)) {
$this->stack = new StackUri($stack);
} else {
if ('object' == \gettype($stack)) {
$given = \get_class($stack);
} else {
$given = \gettype($stack);
}
throw new \RuntimeException('Stack needs to be StackUri or string. '.$given.' given.');
}
} | @since 1.2.0
@param string|StackUri $stack
@throws \RuntimeException |
public function addQuery(array $query) : RequestInterface
{
$this->query = array_merge($this->query, $query);
return $this;
} | {@inheritdoc} |
public function toUri() : string
{
$this->resourceObject->uri->query = $this->query;
return (string) $this->resourceObject->uri;
} | {@inheritdoc} |
public function linkSelf(string $linkKey) : RequestInterface
{
$this->links[] = new LinkType($linkKey, LinkType::SELF_LINK);
return $this;
} | {@inheritdoc} |
public function linkNew(string $linkKey) : RequestInterface
{
$this->links[] = new LinkType($linkKey, LinkType::NEW_LINK);
return $this;
} | {@inheritdoc} |
public function linkCrawl(string $linkKey) : RequestInterface
{
$this->links[] = new LinkType($linkKey, LinkType::CRAWL_LINK);
return $this;
} | {@inheritdoc} |
public function render(ResourceObject $ro)
{
list($ro, $body) = $this->valuate($ro);
$method = 'on' . ucfirst($ro->uri->method);
$hasMethod = method_exists($ro, $method);
$annotations = $hasMethod ? $this->reader->getMethodAnnotations(new \ReflectionMethod($ro, $method)) : [];
/* @var $annotations Link[] */
$hal = $this->getHal($ro->uri, $body, $annotations);
$ro->view = $hal->asJson(true) . PHP_EOL;
$ro->headers['Content-Type'] = 'application/hal+json';
return $ro->view;
} | {@inheritdoc}
@throws \RuntimeException |
public function onPostPackageEvent(\Composer\Installer\PackageEvent $event)
{
$package = $this->getDrupalPackage($event->getOperation());
if ($package) {
if (!$this->isPackageSupported($package)) {
$this->unsupportedPackages[$package->getName()] = $package;
}
}
} | Adds package to $this->unsupportedPackages if applicable.
@param \Composer\Installer\PackageEvent $event |
protected function isPackageSupported($package)
{
$extra = $package->getExtra();
if (!empty($extra['drupal']['security-coverage']['status'])
&& $extra['drupal']['security-coverage']['status'] == 'not-covered') {
return false;
}
return true;
} | Checks to see if this Drupal package is supported by the Drupal Security Team.
@param \Composer\Package\PackageInterface $package
@return bool |
public function onPostCmdEvent(\Composer\Script\Event $event)
{
if (!empty($this->unsupportedPackages)) {
$this->io->write(
'<error>You are using Drupal packages that are not supported by the Drupal Security Team!</error>'
);
foreach ($this->unsupportedPackages as $package_name => $package) {
$extra = $package->getExtra();
$this->io->write(
" - <comment>$package_name:{$package->getVersion()}</comment>: {$extra['drupal']['security-coverage']['message']}"
);
}
$this->io->write(
'<comment>See https://www.drupal.org/security-advisory-policy for more information.</comment>'
);
}
} | Execute blt update after update command has been executed, if applicable.
@param \Composer\Script\Event $event |
protected function getDrupalPackage($operation)
{
if ($operation instanceof InstallOperation) {
$package = $operation->getPackage();
} elseif ($operation instanceof UpdateOperation) {
$package = $operation->getTargetPackage();
}
if ($this->isDrupalPackage($package)) {
return $package;
}
return null;
} | Gets the package if it is a Drupal related package.
@param $operation
@return mixed
If the package is a Drupal package, it will be returned. Otherwise, NULL. |
protected function isDrupalPackage($package)
{
if (isset($package) && $package instanceof PackageInterface && strstr($package->getName(), 'drupal/')) {
return true;
}
return false;
} | Checks to see if a given package is a Drupal package.
@param $package
@return bool
TRUE if the package is a Drupal package. |
public function generateNew(ClassName $targetName): SourceCode
{
$builder = SourceCodeBuilder::create();
$builder->namespace($targetName->namespace());
$classPrototype = $builder->class($targetName->short());
return SourceCode::fromString(
(string) $this->renderer->render($builder->build())
);
} | {@inheritDoc} |
public function generateFromExisting(ClassName $existingClass, ClassName $targetName): SourceCode
{
$existingClass = $this->reflector->reflectClass(ReflectionClassName::fromString((string) $existingClass));
/** @var SourceCodeBuilder $sourceBuilder */
$sourceBuilder = SourceCodeBuilder::create();
$sourceBuilder->namespace($targetName->namespace());
$interfaceBuilder = $sourceBuilder->interface($targetName->short());
$useClasses = [];
/** @var ReflectionMethod $method */
foreach ($existingClass->methods()->byVisibilities([ Visibility::public() ]) as $method) {
if ($method->name() === '__construct') {
continue;
}
$methodBuilder = $interfaceBuilder->method($method->name());
$methodBuilder->visibility((string) $method->visibility());
if ($method->docblock()->isDefined()) {
$methodBuilder->docblock($method->docblock()->formatted());
}
if ($method->returnType()->isDefined()) {
$methodBuilder->returnType($method->returnType()->short());
if ($method->returnType()->isClass()) {
$sourceBuilder->use($method->returnType());
}
}
/** @var ReflectionParameter $parameter */
foreach ($method->parameters() as $parameter) {
$parameterBuilder = $methodBuilder->parameter($parameter->name());
if ($parameter->type()->isDefined()) {
if ($parameter->type()->isPrimitive()) {
$parameterBuilder->type($parameter->type()->primitive());
} else {
$className = $parameter->type()->className();
if ($className) {
$parameterBuilder->type($className->short());
$paramClassName = $parameter->type()->className();
if ($paramClassName) {
$useClasses[$paramClassName->__toString()] = true;
}
}
}
if ($parameter->default()->isDefined()) {
$parameterBuilder->defaultValue($parameter->default()->value());
}
}
}
}
foreach (array_keys($useClasses) as $useClass) {
$sourceBuilder->use($useClass);
}
return SourceCode::fromString($this->renderer->render($sourceBuilder->build()));
} | {@inheritDoc} |
protected function renderDataCellContent($row, $data)
{
/* @var $am CAuthManager|AuthBehavior */
$am = Yii::app()->getAuthManager();
$labelType = $this->active || $am->hasParent($this->itemName, $data['name']) || $am->hasChild(
$this->itemName,
$data['name']
) ? 'info' : '';
/* @var $controller AuthItemController */
$controller = $this->grid->getController();
echo TbHtml::labelTb(
$controller->getItemTypeText($data['item']->type),
array(
'color' => $labelType,
)
);
} | Renders the data cell content.
@param integer $row the row number (zero-based).
@param mixed $data the data associated with the row. |
public function apply(Rule $rule, $value)
{
if ($this->useEncoding($rule)) {
return mb_strtoupper((string) $value, $rule->encoding);
}
return strtoupper((string) $value);
} | {@inheritDoc}
@param \DMS\Filter\Rules\ToUpper $rule |
public function indexBy($column)
{
if (!$this->asArray) {
return parent::indexBy($column);
}
/** @var DynamicActiveRecord $modelClass */
$modelClass = $this->modelClass;
$this->indexBy = function ($row) use ($column, $modelClass) {
if (isset($row[$column])) {
return $row[$column];
}
$dynamicColumn = $modelClass::dynamicColumn();
if (!isset($row[$dynamicColumn])) {
throw new UnknownPropertyException("Dynamic column {$dynamicColumn} does not exist - wasn't set in select");
}
$dynamicAttributes = DynamicActiveRecord::dynColDecode($row[$dynamicColumn]);
$value = $this->getDotNotatedValue($dynamicAttributes, $column);
return $value;
};
return $this;
} | Converts the indexBy column name an anonymous function that writes rows to the
result array indexed an attribute name that may be in dotted notation.
@param callable|string $column name of the column by which the query results should be indexed
@return $this |
public function prepare($builder)
{
/** @var DynamicActiveRecord $modelClass */
$modelClass = $this->modelClass;
$this->_dynamicColumn = $modelClass::dynamicColumn();
if (empty($this->_dynamicColumn)) {
/** @var string $modelClass */
throw new \yii\base\InvalidConfigException(
$modelClass . '::dynamicColumn() must return an attribute name'
);
}
if (empty($this->select)) {
$this->select[] = '*';
}
if (is_array($this->select) && in_array('*', $this->select)) {
$db = $modelClass::getDb();
$this->select[$this->_dynamicColumn] =
'COLUMN_JSON(' . $db->quoteColumnName($this->_dynamicColumn) . ')';
}
return parent::prepare($builder);
} | Maria-specific preparation for building a query that includes a dynamic column.
@param \yii\db\QueryBuilder $builder
@return \yii\db\Query
@throws \yii\base\Exception
@throws \yii\base\InvalidConfigException |
protected function getDotNotatedValue($array, $attribute)
{
$pieces = explode('.', $attribute);
foreach ($pieces as $piece) {
if (!is_array($array) || !array_key_exists($piece, $array)) {
return null;
}
$array = $array[$piece];
}
return $array;
} | Returns the value of the element in an array refereced by a dot-notated attribute name.
@param array $array an array of attributes and values, possibly nested
@param string $attribute the attribute name in dotted notation
@return mixed|null the element in $array referenced by $attribute or null if no such
element exists |
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('surfnet_saml');
$this->addHostedSection($rootNode);
$this->addRemoteSection($rootNode);
return $treeBuilder;
} | {@inheritdoc} |
protected function renderDataCellContent($row, $data)
{
/* @var $am CAuthManager|AuthBehavior */
$am = Yii::app()->getAuthManager();
$linkCssClass = $this->active || $am->hasParent($this->itemName, $data['name']) || $am->hasChild(
$this->itemName,
$data['name']
) ? 'active' : 'disabled';
/* @var $controller AuthItemController */
$controller = $this->grid->getController();
echo CHtml::link(
$data['item']->description,
array('/auth/' . $controller->getItemControllerId($data['item']->type) . '/view', 'name' => $data['name']),
array('class' => $linkCssClass)
);
} | Renders the data cell content.
@param integer $row the row number (zero-based).
@param mixed $data the data associated with the row. |
public function getAttribute($name)
{
try {
return parent::__get($name);
} catch (UnknownPropertyException $ignore) {
}
$path = explode('.', $name);
$ref = &$this->_dynamicAttributes;
foreach ($path as $key) {
if (!isset($ref[$key])) {
return null;
}
$ref = &$ref[$key];
}
return $ref;
} | Returns a model attribute value.
@param string $name attribute name, use dotted notation for structured attributes.
@return mixed|null the attribute value or null if the attribute does not exist |
public function setAttribute($name, $value)
{
try {
parent::__set($name, $value);
return;
} catch (UnknownPropertyException $ignore) {
}
$path = explode('.', $name);
$ref = &$this->_dynamicAttributes;
// Walk forwards through $path to find the deepest key already set.
do {
$key = $path[0];
if (isset($ref[$key])) {
$ref = &$ref[$key];
array_shift($path);
} else {
break;
}
} while ($path);
// If the whole path already existed then we can just set it.
if (!$path) {
$ref = $value;
return;
}
// There is remaining path so we have to set a new leaf with the first
// part of the remaining path as key. But first, if there is any path
// beyond that then we need build an array to set as the new leaf value.
while (count($path) > 1) {
$key = array_pop($path);
$value = [$key => $value];
}
$ref[$path[0]] = $value;
} | Sets a model attribute.
@param string $name attribute name, use dotted notation for structured attributes.
@param mixed $value the attribute value. A value of null effectively unsets the attribute. |
public function issetAttribute($name)
{
try {
if (parent::__get($name) !== null) {
return true;
}
} catch (Exception $ignore) {
}
$path = explode('.', $name);
$ref = &$this->_dynamicAttributes;
foreach ($path as $key) {
if (!isset($ref[$key])) {
return false;
}
$ref = &$ref[$key];
}
return true;
} | Returns if a model attribute is set.
@param string $name attribute name, use dotted notation for structured attributes.
@return bool true if the attribute is set |
public function unsetAttribute($name)
{
try {
parent::__unset($name);
} catch (\Exception $ignore) {
}
if ($this->issetAttribute($name)) {
$this->setAttribute($name, null);
}
} | Unset a model attribute.
@param string $name attribute name, use dotted notation for structured attributes. |
protected static function dotKeyValues($prefix, $array)
{
$fields = [];
foreach ($array as $key => $value) {
if (is_string($key)) {
$newPos = $prefix . '.' . $key;
if (is_array($value)) {
$fields = array_merge($fields, static::dotKeyValues($newPos, $value));
} else {
$fields[$newPos] = $value;
}
}
}
return $fields;
} | Convert a nested array to a map of dot-notation keys to values.
@param string $prefix Prefix returned array keys with this string
@param array $array Nested array of attributeName => value pairs
@return array Map of keys in dotted notation to corresponding values |
public function dotAttributeNames()
{
return array_merge(
array_values(parent::fields()),
array_keys(static::dotKeyValues(static::dynamicColumn(), $this->_dynamicAttributes))
);
} | Return a list of all model attribute names recursing structured dynamic attributes.
@return array an array of all attribute names in dotted notation
@throws Exception |
public static function columnExpression($name, $type = 'char')
{
$sql = '[[' . static::dynamicColumn() . ']]';
$parts = explode('.', $name);
$lastPart = array_pop($parts);
foreach ($parts as $column) {
$sql = "COLUMN_GET($sql, '$column' AS BINARY)";
}
$sql = "COLUMN_GET($sql, '$lastPart' AS $type)";
return $sql;
} | Generate an SQL expression referring to the given dynamic column.
@param string $name Attribute name
@param string $type SQL datatype type
@return string a Maria COLUMN_GET expression |
public static function encodeForMaria($value)
{
return is_string($value)
&& (!mb_check_encoding($value, 'UTF-8') || strpos($value, self::DATA_URI_PREFIX) === 0)
? self::DATA_URI_PREFIX . base64_encode($value)
: $value;
} | Encode as data URIs strings that JSON cannot express.
@param mixed $value a value to encode
@return string the encoded data URI |
public static function decodeForMaria($value)
{
return is_string($value) && strpos($value, self::DATA_URI_PREFIX) === 0
? file_get_contents($value)
: $value;
} | Decode strings encoded as data URIs.
@param string $value the data URI to decode
@return string the decoded value |
protected static function walk(& $array, $method)
{
if (is_scalar($array)) {
$array = static::$method($array);
return;
}
$replacements = [];
foreach ($array as $key => & $value) {
if (is_scalar($value) || $value === null) {
$value = static::$method($value);
} else {
static::walk($value, $method);
}
$newKey = static::$method($key);
if ($newKey !== $key) {
$replacements[$newKey] = $value;
unset($array[$key]);
}
}
foreach ($replacements as $key => $value2) {
$array[$key] = $value2;
}
} | Replacement for PHP's array walk and map builtins.
@param array $array An array to walk, which may be nested
@param callable $method A method to map on the array |
protected static function dynColSqlMaria(array $attrs, & $params)
{
$sql = [];
foreach ($attrs as $key => $value) {
if (is_object($value) && !($value instanceof ValueExpression)) {
$value = method_exists($value, 'toArray') ? $value->toArray() : (array) $value;
}
if ($value === [] || $value === null) {
continue;
}
$phKey = static::placeholder();
$phValue = static::placeholder();
$sql[] = $phKey;
$params[$phKey] = $key;
if ($value instanceof ValueExpression || is_float($value)) {
$sql[] = $value;
} elseif (is_scalar($value)) {
$sql[] = $phValue;
$params[$phValue] = $value;
} elseif (is_array($value)) {
$sql[] = static::dynColSqlMaria($value, $params);
}
}
return $sql === [] ? 'null' : 'COLUMN_CREATE(' . implode(',', $sql) . ')';
} | Creates the SQL and parameter bindings for setting dynamic attributes
in a DB record as Dynamic Columns in Maria.
@param array $attrs the dynamic attributes, which may be nested
@param array $params expression parameters for binding, passed by reference
@return string SQL for a DB Expression
@throws \yii\base\Exception |
public static function dynColExpression($attrs) {
if (!$attrs) {
return null;
}
$params = [];
// todo For now we only have Maria. Add PgSQL and generic JSON.
static::encodeArrayForMaria($attrs);
$sql = static::dynColSqlMaria($attrs, $params);
return new \yii\db\Expression($sql, $params);
} | Creates a dynamic column SQL expression representing the given attributes.
@param array $attrs the dynamic attributes, which may be nested
@return null|\yii\db\Expression |
public static function dynColDecode($encoded)
{
// Maria has a bug in its COLUMN_JSON funcion in which it fails to escape the
// control characters U+0000 through U+001F. This causes JSON decoders to fail.
// This workaround escapes those characters.
$encoded = preg_replace_callback(
'/[\x00-\x1f]/',
function ($matches) {
return sprintf('\u00%02x', ord($matches[0]));
},
$encoded
);
$decoded = json_decode($encoded, true);
if ($decoded) {
static::decodeArrayForMaria($decoded);
}
return $decoded;
} | Decode a serialized blob of dynamic attributes.
At present the only supported input format is JSON returned from Maria. It may work
also for PostgreSQL.
@param string $encoded Serialized array of attributes in DB-specific form
@return array Dynamic attributes in name => value pairs (possibly nested) |
public function beforeSave($insert)
{
if (!parent::beforeSave($insert)) {
return false;
}
$this->setAttribute(static::dynamicColumn(), static::dynColExpression($this->_dynamicAttributes));
return true;
} | @param bool $insert
@return bool
@throws Exception |
public static function populateRecord($record, $row)
{
$dynCol = static::dynamicColumn();
if (isset($row[$dynCol])) {
$record->_dynamicAttributes = static::dynColDecode($row[$dynCol]);
}
parent::populateRecord($record, $row);
} | @param DynamicActiveRecord $record
@param array $row
@throws Exception |
public function addAttributeDefinition(AttributeDefinition $attributeDefinition)
{
if (isset($this->attributeDefinitionsByName[$attributeDefinition->getName()])) {
throw new LogicException(sprintf(
'Cannot add attribute "%s" as it has already been added',
$attributeDefinition->getName()
));
}
$this->attributeDefinitionsByName[$attributeDefinition->getName()] = $attributeDefinition;
if ($attributeDefinition->hasUrnMace()) {
$this->attributeDefinitionsByUrn[$attributeDefinition->getUrnMace()] = $attributeDefinition;
}
if ($attributeDefinition->hasUrnOid()) {
$this->attributeDefinitionsByUrn[$attributeDefinition->getUrnOid()] = $attributeDefinition;
}
} | @param AttributeDefinition $attributeDefinition
We store the definitions indexed both by name and by urn to ensure speedy lookups due to the amount of
definitions and the amount of usages of the lookups |
protected function renderDataCellContent($row, $data)
{
/* @var $am CAuthManager|AuthBehavior */
$am = Yii::app()->getAuthManager();
/* @var $controller AssignmentController */
$controller = $this->grid->getController();
$assignments = $am->getAuthAssignments($data->{$this->idColumn});
$permissions = $am->getItemsPermissions(array_keys($assignments));
foreach ($permissions as $itemPermission) {
echo $itemPermission['item']->description;
echo ' <small>' . $controller->getItemTypeText($itemPermission['item']->type, false) . '</small><br />';
}
} | Renders the data cell content.
@param integer $row the row number (zero-based).
@param mixed $data the data associated with the row. |
public function apply(Rule $rule, $value)
{
return htmlentities($value, $rule->flags, $rule->encoding, $rule->doubleEncode);
} | {@inheritDoc}
@param \DMS\Filter\Rules\HtmlEntities $rule |
public function apply(Rule $rule, $value)
{
//trim() only operates in default mode
//if no second argument is passed, it
//cannot be passed as null
if ($rule->charlist === null) {
return trim($value);
}
return trim($value, $rule->charlist);
} | {@inheritDoc}
@param \DMS\Filter\Rules\Trim $rule |
public function init()
{
$this->setImport(
array(
'auth.components.*',
'auth.controllers.*',
'auth.models.*',
'auth.widgets.*',
)
);
$this->registerCss();
$this->flashKeys = array_merge(
$this->flashKeys,
array(
'error' => 'error',
'info' => 'info',
'success' => 'success',
'warning' => 'warning',
)
);
if (isset($this->viewDir)) {
if (strpos($this->viewDir, '.')) {
$this->viewDir = Yii::getPathOfAlias($this->viewDir);
}
$this->setLayoutPath($this->viewDir . DIRECTORY_SEPARATOR . 'layouts');
$this->setViewPath($this->viewDir);
}
} | Initializes the module. |
public function beforeControllerAction($controller, $action)
{
if (parent::beforeControllerAction($controller, $action)) {
$user = Yii::app()->getUser();
if ($user instanceof AuthWebUser) {
if ($user->isAdmin) {
return true;
} elseif ($user->isGuest) {
$user->loginRequired();
}
} else {
throw new CException('WebUser component is not an instance of AuthWebUser.');
}
}
throw new CHttpException(401, Yii::t('AuthModule.main', 'Access denied.'));
} | The pre-filter for controller actions.
@param CController $controller the controller.
@param CAction $action the action.
@return boolean whether the action should be executed.
@throws CException|CHttpException if user is denied access. |
protected function getAssetsUrl()
{
if (isset($this->_assetsUrl)) {
return $this->_assetsUrl;
} else {
$assetsPath = Yii::getPathOfAlias('auth.assets');
$assetsUrl = Yii::app()->assetManager->publish($assetsPath, false, -1, $this->forceCopyAssets);
return $this->_assetsUrl = $assetsUrl;
}
} | Returns the URL to the published assets folder.
@return string the URL. |
public function getInputType()
{
switch (true) {
case $this->callback instanceof Closure:
return self::CLOSURE_TYPE;
case is_callable($this->callback, false):
return self::CALLABLE_TYPE;
case is_string($this->callback):
return self::SELF_METHOD_TYPE;
}
throw new InvalidCallbackException(
"The input provided for Callback filter is not supported or the callable not valid.
Please refer to the class documentation."
);
} | Figures out which type of input was provided
@return string
@throws \DMS\Filter\Exception\InvalidCallbackException |
protected function fetchData()
{
if (empty($this->_items) && $this->type !== null) {
$authItems = Yii::app()->authManager->getAuthItems($this->type);
$this->setAuthItems($authItems);
}
return $this->_items;
} | Fetches the data from the persistent data storage.
@return array list of data items |
public function apply(Rule $rule, $value)
{
//Check for Whitespace support
$whitespaceChar = ($rule->allowWhitespace)? " ":"";
$rule->unicodePattern = '/[^\p{N}' . $whitespaceChar . ']/';
$rule->pattern = '/[^0-9' . $whitespaceChar . ']/';
return parent::apply($rule, $value);
} | {@inheritDoc}
@param \DMS\Filter\Rules\Digits $rule |
public function apply(Rule $rule, $value)
{
if (is_array($value) || is_object($value)) {
return null;
}
return floatval($value);
} | {@inheritDoc} |
public function applyFilterRules($property, $filterRules = array())
{
foreach ($filterRules as $rule) {
$this->applyFilterRule($property, $rule);
}
} | Applies the selected rules to a property in the object
@param string $property
@param array $filterRules |
public function applyFilterRule($property, Rules\Rule $filterRule)
{
if ($this->filterLoader === null) {
throw new \UnexpectedValueException("A FilterLoader must be provided");
}
$value = $this->getPropertyValue($property);
$filter = $this->filterLoader->getFilterForRule($filterRule);
if ($filter instanceof ObjectAwareFilter) {
$filter->setCurrentObject($this->object);
}
$filteredValue = $filter->apply($filterRule, $value);
$this->setPropertyValue($property, $filteredValue);
} | Applies a Filtering Rule to a property
@param string $property
@param Rules\Rule $filterRule
@throws \UnexpectedValueException |
private function setPropertyValue($propertyName, $value)
{
$this->getAccessibleReflectionProperty($propertyName)
->setValue($this->object, $value);
} | Overrides the value of a property, overcoming visibility problems
@param string$propertyName
@param mixed $value |
private function getAccessibleReflectionProperty($propertyName)
{
$property = $this->reflClass->getProperty($propertyName);
$property->setAccessible(true);
return $property;
} | Retrieves a property from the object and makes it visible
@param string $propertyName
@return \ReflectionProperty |
public function receiveSignedAuthnRequestFrom(Request $request)
{
if (!$this->entityRepository) {
throw new LogicException(
'Could not receive AuthnRequest from HTTP Request: a ServiceProviderRepository must be configured'
);
}
if (!$request->isMethod(Request::METHOD_GET)) {
throw new BadRequestHttpException(sprintf(
'Could not receive AuthnRequest from HTTP Request: expected a GET method, got %s',
$request->getMethod()
));
}
$requestUri = $request->getRequestUri();
if (strpos($requestUri, '?') === false) {
throw new BadRequestHttpException(
'Could not receive AuthnRequest from HTTP Request: expected query parameters, none found'
);
}
list(, $rawQueryString) = explode('?', $requestUri);
$query = ReceivedAuthnRequestQueryString::parse($rawQueryString);
if (!$query->isSigned()) {
throw new UnsignedRequestException('The SAMLRequest is expected to be signed but it was not');
}
if (!$this->signatureVerifier->verifySignatureAlgorithmSupported($query)) {
throw new UnsupportedSignatureException(
$query->getSignatureAlgorithm()
);
}
$authnRequest = ReceivedAuthnRequest::from($query->getDecodedSamlRequest());
$currentUri = $this->getFullRequestUri($request);
if (!$authnRequest->getDestination() === $currentUri) {
throw new BadRequestHttpException(sprintf(
'Actual Destination "%s" does not match the AuthnRequest Destination "%s"',
$currentUri,
$authnRequest->getDestination()
));
}
if (!$this->entityRepository->hasServiceProvider($authnRequest->getServiceProvider())) {
throw new UnknownServiceProviderException($authnRequest->getServiceProvider());
}
$serviceProvider = $this->entityRepository->getServiceProvider($authnRequest->getServiceProvider());
// Note: verifyIsSignedBy throws an Exception when the signature does not match.
if (!$this->signatureVerifier->verifyIsSignedBy($query, $serviceProvider)) {
throw new SignatureValidationFailedException(
'Validation of the signature in the AuthnRequest failed'
);
}
return $authnRequest;
} | @param Request $request
@return ReceivedAuthnRequest
@SuppressWarnings(PHPMD.NPathComplexity) |