repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
Galbar/JsonPath-PHP
src/Galbar/Utilities/ArraySlice.php
ArraySlice.slice
public static function slice(&$array, $start = null, $stop = null, $step = null, $byReference = false) { $result = array(); $indexes = self::sliceIndices(count($array), $start, $stop, $step); if ($byReference) { foreach ($indexes as $i) { $result[] = &$array[$i]; } } else { foreach ($indexes as $i) { $result[] = $array[$i]; } } return $result; }
php
public static function slice(&$array, $start = null, $stop = null, $step = null, $byReference = false) { $result = array(); $indexes = self::sliceIndices(count($array), $start, $stop, $step); if ($byReference) { foreach ($indexes as $i) { $result[] = &$array[$i]; } } else { foreach ($indexes as $i) { $result[] = $array[$i]; } } return $result; }
[ "public", "static", "function", "slice", "(", "&", "$", "array", ",", "$", "start", "=", "null", ",", "$", "stop", "=", "null", ",", "$", "step", "=", "null", ",", "$", "byReference", "=", "false", ")", "{", "$", "result", "=", "array", "(", ")", ";", "$", "indexes", "=", "self", "::", "sliceIndices", "(", "count", "(", "$", "array", ")", ",", "$", "start", ",", "$", "stop", ",", "$", "step", ")", ";", "if", "(", "$", "byReference", ")", "{", "foreach", "(", "$", "indexes", "as", "$", "i", ")", "{", "$", "result", "[", "]", "=", "&", "$", "array", "[", "$", "i", "]", ";", "}", "}", "else", "{", "foreach", "(", "$", "indexes", "as", "$", "i", ")", "{", "$", "result", "[", "]", "=", "$", "array", "[", "$", "i", "]", ";", "}", "}", "return", "$", "result", ";", "}" ]
Implements the Python slice behaviour * a[1:2:3] => slice($a, 1, 2, 3) * a[1:4] => slice($a, 1, 4) * a[3::2] => slice($a, 3, null, 2) If $byReference is true, then the elements of the resulting array will be references to the initial array. @param array $array array @param int|null $start start @param int|null $stop stop @param int|null $step step @param bool $byReference byReference @return void
[ "Implements", "the", "Python", "slice", "behaviour" ]
train
https://github.com/Galbar/JsonPath-PHP/blob/ea104b4f835388018f4bd529a2dace88617d5be6/src/Galbar/Utilities/ArraySlice.php#L41-L55
Galbar/JsonPath-PHP
src/Galbar/JsonPath/JsonObject.php
JsonObject.get
public function get($jsonPath) { $this->hasDiverged = false; $result = $this->getReal($this->jsonObject, $jsonPath); if ($this->smartGet && $result !== false && !$this->hasDiverged) { return $result[0]; } return $result; }
php
public function get($jsonPath) { $this->hasDiverged = false; $result = $this->getReal($this->jsonObject, $jsonPath); if ($this->smartGet && $result !== false && !$this->hasDiverged) { return $result[0]; } return $result; }
[ "public", "function", "get", "(", "$", "jsonPath", ")", "{", "$", "this", "->", "hasDiverged", "=", "false", ";", "$", "result", "=", "$", "this", "->", "getReal", "(", "$", "this", "->", "jsonObject", ",", "$", "jsonPath", ")", ";", "if", "(", "$", "this", "->", "smartGet", "&&", "$", "result", "!==", "false", "&&", "!", "$", "this", "->", "hasDiverged", ")", "{", "return", "$", "result", "[", "0", "]", ";", "}", "return", "$", "result", ";", "}" ]
Returns an array containing references to the objects that match the JsonPath. If the result is empty returns false. If smartGet was set to true when creating the instance and the JsonPath given does not branch, it will return the value instead of an array of one element. @param string $jsonPath jsonPath @return mixed
[ "Returns", "an", "array", "containing", "references", "to", "the", "objects", "that", "match", "the", "JsonPath", ".", "If", "the", "result", "is", "empty", "returns", "false", "." ]
train
https://github.com/Galbar/JsonPath-PHP/blob/ea104b4f835388018f4bd529a2dace88617d5be6/src/Galbar/JsonPath/JsonObject.php#L267-L275
Galbar/JsonPath-PHP
src/Galbar/JsonPath/JsonObject.php
JsonObject.getJsonObjects
public function getJsonObjects($jsonPath) { $this->hasDiverged = false; $result = $this->getReal($this->jsonObject, $jsonPath); if ($result !== false) { $objs = array(); foreach($result as &$value) { $jsonObject = new JsonObject(null, $this->smartGet); $jsonObject->jsonObject = &$value; $objs[] = $jsonObject; } if ($this->smartGet && !$this->hasDiverged) { return $objs[0]; } return $objs; } return $result; }
php
public function getJsonObjects($jsonPath) { $this->hasDiverged = false; $result = $this->getReal($this->jsonObject, $jsonPath); if ($result !== false) { $objs = array(); foreach($result as &$value) { $jsonObject = new JsonObject(null, $this->smartGet); $jsonObject->jsonObject = &$value; $objs[] = $jsonObject; } if ($this->smartGet && !$this->hasDiverged) { return $objs[0]; } return $objs; } return $result; }
[ "public", "function", "getJsonObjects", "(", "$", "jsonPath", ")", "{", "$", "this", "->", "hasDiverged", "=", "false", ";", "$", "result", "=", "$", "this", "->", "getReal", "(", "$", "this", "->", "jsonObject", ",", "$", "jsonPath", ")", ";", "if", "(", "$", "result", "!==", "false", ")", "{", "$", "objs", "=", "array", "(", ")", ";", "foreach", "(", "$", "result", "as", "&", "$", "value", ")", "{", "$", "jsonObject", "=", "new", "JsonObject", "(", "null", ",", "$", "this", "->", "smartGet", ")", ";", "$", "jsonObject", "->", "jsonObject", "=", "&", "$", "value", ";", "$", "objs", "[", "]", "=", "$", "jsonObject", ";", "}", "if", "(", "$", "this", "->", "smartGet", "&&", "!", "$", "this", "->", "hasDiverged", ")", "{", "return", "$", "objs", "[", "0", "]", ";", "}", "return", "$", "objs", ";", "}", "return", "$", "result", ";", "}" ]
Return an array of new JsonObjects representing the results of the given JsonPath. These objects contain references to the elements in the original JsonObject. This is affected by smartGet the same way JsonObject::get is affected This can cause JsonObject to have actual values (not object/array) as root. This is useful when you want to work with a subelement of the root object and you want to edit (add, set, remove) values in that subelement and that these changes also affect the root object. @param string $jsonPath jsonPath @return mixed
[ "Return", "an", "array", "of", "new", "JsonObjects", "representing", "the", "results", "of", "the", "given", "JsonPath", ".", "These", "objects", "contain", "references", "to", "the", "elements", "in", "the", "original", "JsonObject", "." ]
train
https://github.com/Galbar/JsonPath-PHP/blob/ea104b4f835388018f4bd529a2dace88617d5be6/src/Galbar/JsonPath/JsonObject.php#L293-L310
Galbar/JsonPath-PHP
src/Galbar/JsonPath/JsonObject.php
JsonObject.set
public function set($jsonPath, $value) { $result = $this->getReal($this->jsonObject, $jsonPath, true); if ($result !== false) { foreach ($result as &$element) { $element = $value; } } return $this; }
php
public function set($jsonPath, $value) { $result = $this->getReal($this->jsonObject, $jsonPath, true); if ($result !== false) { foreach ($result as &$element) { $element = $value; } } return $this; }
[ "public", "function", "set", "(", "$", "jsonPath", ",", "$", "value", ")", "{", "$", "result", "=", "$", "this", "->", "getReal", "(", "$", "this", "->", "jsonObject", ",", "$", "jsonPath", ",", "true", ")", ";", "if", "(", "$", "result", "!==", "false", ")", "{", "foreach", "(", "$", "result", "as", "&", "$", "element", ")", "{", "$", "element", "=", "$", "value", ";", "}", "}", "return", "$", "this", ";", "}" ]
Sets all elements that result from the $jsonPath query to $value. This method will create previously non-existent JSON objects if the path contains them (p.e. if quering '$.a' results in false, when setting '$.a.b' to a value '$.a' will be created as a result of this). This method returns $this to enable fluent interface. @param string $jsonPath jsonPath @param mixed $value value @return JsonObject
[ "Sets", "all", "elements", "that", "result", "from", "the", "$jsonPath", "query", "to", "$value", ".", "This", "method", "will", "create", "previously", "non", "-", "existent", "JSON", "objects", "if", "the", "path", "contains", "them", "(", "p", ".", "e", ".", "if", "quering", "$", ".", "a", "results", "in", "false", "when", "setting", "$", ".", "a", ".", "b", "to", "a", "value", "$", ".", "a", "will", "be", "created", "as", "a", "result", "of", "this", ")", "." ]
train
https://github.com/Galbar/JsonPath-PHP/blob/ea104b4f835388018f4bd529a2dace88617d5be6/src/Galbar/JsonPath/JsonObject.php#L328-L337
Galbar/JsonPath-PHP
src/Galbar/JsonPath/JsonObject.php
JsonObject.add
public function add($jsonPath, $value, $field=null) { $result = $this->getReal($this->jsonObject, $jsonPath, true); foreach ($result as &$element) { if (is_array($element)) { if ($field == null) { $element[] = $value; } else { $element[$field] = $value; } } } return $this; }
php
public function add($jsonPath, $value, $field=null) { $result = $this->getReal($this->jsonObject, $jsonPath, true); foreach ($result as &$element) { if (is_array($element)) { if ($field == null) { $element[] = $value; } else { $element[$field] = $value; } } } return $this; }
[ "public", "function", "add", "(", "$", "jsonPath", ",", "$", "value", ",", "$", "field", "=", "null", ")", "{", "$", "result", "=", "$", "this", "->", "getReal", "(", "$", "this", "->", "jsonObject", ",", "$", "jsonPath", ",", "true", ")", ";", "foreach", "(", "$", "result", "as", "&", "$", "element", ")", "{", "if", "(", "is_array", "(", "$", "element", ")", ")", "{", "if", "(", "$", "field", "==", "null", ")", "{", "$", "element", "[", "]", "=", "$", "value", ";", "}", "else", "{", "$", "element", "[", "$", "field", "]", "=", "$", "value", ";", "}", "}", "}", "return", "$", "this", ";", "}" ]
Append a new value to all json objects/arrays that match the $jsonPath path. If $field is not null, the new value will be added with $field as key (this will transform json arrays into objects). This method returns $this to enable fluent interface. @param string $jsonPath jsonPath @param mixed $value value @param string $field field @return JsonObject
[ "Append", "a", "new", "value", "to", "all", "json", "objects", "/", "arrays", "that", "match", "the", "$jsonPath", "path", ".", "If", "$field", "is", "not", "null", "the", "new", "value", "will", "be", "added", "with", "$field", "as", "key", "(", "this", "will", "transform", "json", "arrays", "into", "objects", ")", ".", "This", "method", "returns", "$this", "to", "enable", "fluent", "interface", "." ]
train
https://github.com/Galbar/JsonPath-PHP/blob/ea104b4f835388018f4bd529a2dace88617d5be6/src/Galbar/JsonPath/JsonObject.php#L352-L366
Galbar/JsonPath-PHP
src/Galbar/JsonPath/JsonObject.php
JsonObject.remove
public function remove($jsonPath, $field) { $result = $this->getReal($this->jsonObject, $jsonPath); foreach ($result as &$element) { if (is_array($element)) { unset($element[$field]); } } return $this; }
php
public function remove($jsonPath, $field) { $result = $this->getReal($this->jsonObject, $jsonPath); foreach ($result as &$element) { if (is_array($element)) { unset($element[$field]); } } return $this; }
[ "public", "function", "remove", "(", "$", "jsonPath", ",", "$", "field", ")", "{", "$", "result", "=", "$", "this", "->", "getReal", "(", "$", "this", "->", "jsonObject", ",", "$", "jsonPath", ")", ";", "foreach", "(", "$", "result", "as", "&", "$", "element", ")", "{", "if", "(", "is_array", "(", "$", "element", ")", ")", "{", "unset", "(", "$", "element", "[", "$", "field", "]", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Remove $field from json objects/arrays that match $jsonPath path. This method returns $this to enable fluent interface. @param mixed $jsonPath jsonPath @param mixed $field field @return JsonObject
[ "Remove", "$field", "from", "json", "objects", "/", "arrays", "that", "match", "$jsonPath", "path", ".", "This", "method", "returns", "$this", "to", "enable", "fluent", "interface", "." ]
train
https://github.com/Galbar/JsonPath-PHP/blob/ea104b4f835388018f4bd529a2dace88617d5be6/src/Galbar/JsonPath/JsonObject.php#L378-L387
asvae/laravel-api-tester
src/Storages/JsonStorage.php
JsonStorage.get
public function get() { $fullPath = $this->getFilePath(); if ($this->files->exists($fullPath)) { $content = $this->files->get($fullPath); return $this->makeCollection($this->parseResult($content)); } return $this->makeCollection(); }
php
public function get() { $fullPath = $this->getFilePath(); if ($this->files->exists($fullPath)) { $content = $this->files->get($fullPath); return $this->makeCollection($this->parseResult($content)); } return $this->makeCollection(); }
[ "public", "function", "get", "(", ")", "{", "$", "fullPath", "=", "$", "this", "->", "getFilePath", "(", ")", ";", "if", "(", "$", "this", "->", "files", "->", "exists", "(", "$", "fullPath", ")", ")", "{", "$", "content", "=", "$", "this", "->", "files", "->", "get", "(", "$", "fullPath", ")", ";", "return", "$", "this", "->", "makeCollection", "(", "$", "this", "->", "parseResult", "(", "$", "content", ")", ")", ";", "}", "return", "$", "this", "->", "makeCollection", "(", ")", ";", "}" ]
Return array parsed from file content. @return RequestCollection
[ "Return", "array", "parsed", "from", "file", "content", "." ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Storages/JsonStorage.php#L93-L105
asvae/laravel-api-tester
src/Storages/JsonStorage.php
JsonStorage.createDirectoryIfNotExists
protected function createDirectoryIfNotExists() { if (!is_dir($this->getPath())) { $this->files->makeDirectory($this->getPath(), 0755, true); } }
php
protected function createDirectoryIfNotExists() { if (!is_dir($this->getPath())) { $this->files->makeDirectory($this->getPath(), 0755, true); } }
[ "protected", "function", "createDirectoryIfNotExists", "(", ")", "{", "if", "(", "!", "is_dir", "(", "$", "this", "->", "getPath", "(", ")", ")", ")", "{", "$", "this", "->", "files", "->", "makeDirectory", "(", "$", "this", "->", "getPath", "(", ")", ",", "0755", ",", "true", ")", ";", "}", "}" ]
Make directory path if not exists
[ "Make", "directory", "path", "if", "not", "exists" ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Storages/JsonStorage.php#L123-L128
asvae/laravel-api-tester
src/Storages/JsonStorage.php
JsonStorage.parseResult
protected function parseResult($content) { $data = []; foreach (explode(static::ROW_DELIMITER, $content) as $row) { if (empty($row)) { continue; } $data[] = json_decode($row, true); } return $data; }
php
protected function parseResult($content) { $data = []; foreach (explode(static::ROW_DELIMITER, $content) as $row) { if (empty($row)) { continue; } $data[] = json_decode($row, true); } return $data; }
[ "protected", "function", "parseResult", "(", "$", "content", ")", "{", "$", "data", "=", "[", "]", ";", "foreach", "(", "explode", "(", "static", "::", "ROW_DELIMITER", ",", "$", "content", ")", "as", "$", "row", ")", "{", "if", "(", "empty", "(", "$", "row", ")", ")", "{", "continue", ";", "}", "$", "data", "[", "]", "=", "json_decode", "(", "$", "row", ",", "true", ")", ";", "}", "return", "$", "data", ";", "}" ]
Parse result form given string @param $content @return array
[ "Parse", "result", "form", "given", "string" ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Storages/JsonStorage.php#L137-L150
asvae/laravel-api-tester
src/Storages/JsonStorage.php
JsonStorage.prepareContent
private function prepareContent($data) { $content = ''; foreach ($data as $row) { $content .= $this->convertToJson($row) . static::ROW_DELIMITER; } return $content; }
php
private function prepareContent($data) { $content = ''; foreach ($data as $row) { $content .= $this->convertToJson($row) . static::ROW_DELIMITER; } return $content; }
[ "private", "function", "prepareContent", "(", "$", "data", ")", "{", "$", "content", "=", "''", ";", "foreach", "(", "$", "data", "as", "$", "row", ")", "{", "$", "content", ".=", "$", "this", "->", "convertToJson", "(", "$", "row", ")", ".", "static", "::", "ROW_DELIMITER", ";", "}", "return", "$", "content", ";", "}" ]
Prepare content string from given data @param \Traversable|array $data @return string
[ "Prepare", "content", "string", "from", "given", "data" ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Storages/JsonStorage.php#L159-L168
asvae/laravel-api-tester
src/Storages/JsonStorage.php
JsonStorage.convertToJson
private function convertToJson($data) { if (is_array($data)) { return json_encode($data); } if ($data instanceof Jsonable) { return $data->toJson(); } if ($data instanceof Arrayable) { return json_encode($data->toArray()); } return null; }
php
private function convertToJson($data) { if (is_array($data)) { return json_encode($data); } if ($data instanceof Jsonable) { return $data->toJson(); } if ($data instanceof Arrayable) { return json_encode($data->toArray()); } return null; }
[ "private", "function", "convertToJson", "(", "$", "data", ")", "{", "if", "(", "is_array", "(", "$", "data", ")", ")", "{", "return", "json_encode", "(", "$", "data", ")", ";", "}", "if", "(", "$", "data", "instanceof", "Jsonable", ")", "{", "return", "$", "data", "->", "toJson", "(", ")", ";", "}", "if", "(", "$", "data", "instanceof", "Arrayable", ")", "{", "return", "json_encode", "(", "$", "data", "->", "toArray", "(", ")", ")", ";", "}", "return", "null", ";", "}" ]
@param $data @return null|string
[ "@param", "$data" ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Storages/JsonStorage.php#L175-L190
asvae/laravel-api-tester
src/Repositories/RouteDingoRepository.php
RouteDingoRepository.get
public function get($match = [], $except = []) { return $this->routes->filterMatch($match) ->filterExcept($except) ->values(); }
php
public function get($match = [], $except = []) { return $this->routes->filterMatch($match) ->filterExcept($except) ->values(); }
[ "public", "function", "get", "(", "$", "match", "=", "[", "]", ",", "$", "except", "=", "[", "]", ")", "{", "return", "$", "this", "->", "routes", "->", "filterMatch", "(", "$", "match", ")", "->", "filterExcept", "(", "$", "except", ")", "->", "values", "(", ")", ";", "}" ]
@param array $match @param array $except @return \Asvae\ApiTester\Collections\RouteCollection
[ "@param", "array", "$match", "@param", "array", "$except" ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Repositories/RouteDingoRepository.php#L54-L59
asvae/laravel-api-tester
src/Providers/StorageServiceProvide.php
StorageServiceProvide.register
public function register() { // Регистрируем конкретный сторэйдж из списка доступных. $this->app->singleton(StorageInterface::class, function (Container $app) { // Defined driver $selectedDriver = config('api-tester.storage_driver'); $driverClassName = config('api-tester.storage_drivers')[$selectedDriver]; $requestCollection = $app->make(RequestCollection::class); if ($selectedDriver === 'firebase'){ $tokenGenerator = $app->make(TokenGenerator::class); $base = config('api-tester.storage_drivers.firebase.options.base'); return new FireBaseStorage($requestCollection, $tokenGenerator, $base); } if ($selectedDriver === 'file'){ $fileSystem = $app->make(Filesystem::class); $path = config('api-tester.storage_drivers.file.options.path'); return new JsonStorage($fileSystem, $requestCollection, $path); } throw new Exception("Driver $selectedDriver doesn't exist. Use either 'firebase' or 'file'."); }); // Регистрация токен-генератора. Привязывается к ключу а не классу, // чтобы не конфликтовать с пользовательским генератором токенов. $this->app->singleton('api-tester.token_generator', function (Container $app) { $config = $app['config']['api-tester.storage_drivers.firebase.token']; return (new TokenGenerator($config['secret'])) ->setOptions($config['options']) ->setData($config['data']); }); // Подсовываем генератор в сторэйдж $this->app ->when(FireBaseStorage::class) ->needs(TokenGenerator::class) ->give('api-tester.token_generator'); }
php
public function register() { // Регистрируем конкретный сторэйдж из списка доступных. $this->app->singleton(StorageInterface::class, function (Container $app) { // Defined driver $selectedDriver = config('api-tester.storage_driver'); $driverClassName = config('api-tester.storage_drivers')[$selectedDriver]; $requestCollection = $app->make(RequestCollection::class); if ($selectedDriver === 'firebase'){ $tokenGenerator = $app->make(TokenGenerator::class); $base = config('api-tester.storage_drivers.firebase.options.base'); return new FireBaseStorage($requestCollection, $tokenGenerator, $base); } if ($selectedDriver === 'file'){ $fileSystem = $app->make(Filesystem::class); $path = config('api-tester.storage_drivers.file.options.path'); return new JsonStorage($fileSystem, $requestCollection, $path); } throw new Exception("Driver $selectedDriver doesn't exist. Use either 'firebase' or 'file'."); }); // Регистрация токен-генератора. Привязывается к ключу а не классу, // чтобы не конфликтовать с пользовательским генератором токенов. $this->app->singleton('api-tester.token_generator', function (Container $app) { $config = $app['config']['api-tester.storage_drivers.firebase.token']; return (new TokenGenerator($config['secret'])) ->setOptions($config['options']) ->setData($config['data']); }); // Подсовываем генератор в сторэйдж $this->app ->when(FireBaseStorage::class) ->needs(TokenGenerator::class) ->give('api-tester.token_generator'); }
[ "public", "function", "register", "(", ")", "{", "// Регистрируем конкретный сторэйдж из списка доступных.", "$", "this", "->", "app", "->", "singleton", "(", "StorageInterface", "::", "class", ",", "function", "(", "Container", "$", "app", ")", "{", "// Defined driver", "$", "selectedDriver", "=", "config", "(", "'api-tester.storage_driver'", ")", ";", "$", "driverClassName", "=", "config", "(", "'api-tester.storage_drivers'", ")", "[", "$", "selectedDriver", "]", ";", "$", "requestCollection", "=", "$", "app", "->", "make", "(", "RequestCollection", "::", "class", ")", ";", "if", "(", "$", "selectedDriver", "===", "'firebase'", ")", "{", "$", "tokenGenerator", "=", "$", "app", "->", "make", "(", "TokenGenerator", "::", "class", ")", ";", "$", "base", "=", "config", "(", "'api-tester.storage_drivers.firebase.options.base'", ")", ";", "return", "new", "FireBaseStorage", "(", "$", "requestCollection", ",", "$", "tokenGenerator", ",", "$", "base", ")", ";", "}", "if", "(", "$", "selectedDriver", "===", "'file'", ")", "{", "$", "fileSystem", "=", "$", "app", "->", "make", "(", "Filesystem", "::", "class", ")", ";", "$", "path", "=", "config", "(", "'api-tester.storage_drivers.file.options.path'", ")", ";", "return", "new", "JsonStorage", "(", "$", "fileSystem", ",", "$", "requestCollection", ",", "$", "path", ")", ";", "}", "throw", "new", "Exception", "(", "\"Driver $selectedDriver doesn't exist. Use either 'firebase' or 'file'.\"", ")", ";", "}", ")", ";", "// Регистрация токен-генератора. Привязывается к ключу а не классу,", "// чтобы не конфликтовать с пользовательским генератором токенов.", "$", "this", "->", "app", "->", "singleton", "(", "'api-tester.token_generator'", ",", "function", "(", "Container", "$", "app", ")", "{", "$", "config", "=", "$", "app", "[", "'config'", "]", "[", "'api-tester.storage_drivers.firebase.token'", "]", ";", "return", "(", "new", "TokenGenerator", "(", "$", "config", "[", "'secret'", "]", ")", ")", "->", "setOptions", "(", "$", "config", "[", "'options'", "]", ")", "->", "setData", "(", "$", "config", "[", "'data'", "]", ")", ";", "}", ")", ";", "// Подсовываем генератор в сторэйдж", "$", "this", "->", "app", "->", "when", "(", "FireBaseStorage", "::", "class", ")", "->", "needs", "(", "TokenGenerator", "::", "class", ")", "->", "give", "(", "'api-tester.token_generator'", ")", ";", "}" ]
Register the service provider. @return void
[ "Register", "the", "service", "provider", "." ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Providers/StorageServiceProvide.php#L37-L77
asvae/laravel-api-tester
src/Entities/RouteInfo.php
RouteInfo.getMethods
private function getMethods() { // Laravel <5.4 if (method_exists($this->route, 'getMethods')) { return $this->route->getMethods(); } // Laravel 5.4+ return $this->route->methods(); }
php
private function getMethods() { // Laravel <5.4 if (method_exists($this->route, 'getMethods')) { return $this->route->getMethods(); } // Laravel 5.4+ return $this->route->methods(); }
[ "private", "function", "getMethods", "(", ")", "{", "// Laravel <5.4", "if", "(", "method_exists", "(", "$", "this", "->", "route", ",", "'getMethods'", ")", ")", "{", "return", "$", "this", "->", "route", "->", "getMethods", "(", ")", ";", "}", "// Laravel 5.4+", "return", "$", "this", "->", "route", "->", "methods", "(", ")", ";", "}" ]
Cross version get methods. @return array
[ "Cross", "version", "get", "methods", "." ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Entities/RouteInfo.php#L78-L86
asvae/laravel-api-tester
src/Entities/RouteInfo.php
RouteInfo.getUri
protected function getUri(){ if (method_exists($this->route, 'getPath')){ // Laravel <5.4 return $this->route->getPath(); } // Laravel 5.4+ return $this->route->uri(); }
php
protected function getUri(){ if (method_exists($this->route, 'getPath')){ // Laravel <5.4 return $this->route->getPath(); } // Laravel 5.4+ return $this->route->uri(); }
[ "protected", "function", "getUri", "(", ")", "{", "if", "(", "method_exists", "(", "$", "this", "->", "route", ",", "'getPath'", ")", ")", "{", "// Laravel <5.4", "return", "$", "this", "->", "route", "->", "getPath", "(", ")", ";", "}", "// Laravel 5.4+", "return", "$", "this", "->", "route", "->", "uri", "(", ")", ";", "}" ]
Backwards compatible uri getter. @return string
[ "Backwards", "compatible", "uri", "getter", "." ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Entities/RouteInfo.php#L235-L243
asvae/laravel-api-tester
src/Entities/BaseEntity.php
BaseEntity.fill
public function fill(array $data) { $this->attributes = array_merge($this->attributes, $this->filterFillable($data)); }
php
public function fill(array $data) { $this->attributes = array_merge($this->attributes, $this->filterFillable($data)); }
[ "public", "function", "fill", "(", "array", "$", "data", ")", "{", "$", "this", "->", "attributes", "=", "array_merge", "(", "$", "this", "->", "attributes", ",", "$", "this", "->", "filterFillable", "(", "$", "data", ")", ")", ";", "}" ]
Fill attributes that can be filled. @param $data @return void
[ "Fill", "attributes", "that", "can", "be", "filled", "." ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Entities/BaseEntity.php#L49-L52
asvae/laravel-api-tester
src/Collections/RouteCollection.php
RouteCollection.filterMatch
public function filterMatch($patterns) { $patterns = is_string($patterns) ? [$patterns] : $patterns; // String pattern is assumed to be path. foreach ($patterns as $key => $pattern) { if (is_string($pattern)) { $patterns[$key] = ['path' => $pattern]; } } return $this->filter(function ($route) use ($patterns) { // If any of patterns matches - route passes. foreach ($patterns as $pattern) { if ($this->isRouteMatchesPattern($route, $pattern)) { return true; } } // If all patterns don't match - route is filtered out. return false; }); }
php
public function filterMatch($patterns) { $patterns = is_string($patterns) ? [$patterns] : $patterns; // String pattern is assumed to be path. foreach ($patterns as $key => $pattern) { if (is_string($pattern)) { $patterns[$key] = ['path' => $pattern]; } } return $this->filter(function ($route) use ($patterns) { // If any of patterns matches - route passes. foreach ($patterns as $pattern) { if ($this->isRouteMatchesPattern($route, $pattern)) { return true; } } // If all patterns don't match - route is filtered out. return false; }); }
[ "public", "function", "filterMatch", "(", "$", "patterns", ")", "{", "$", "patterns", "=", "is_string", "(", "$", "patterns", ")", "?", "[", "$", "patterns", "]", ":", "$", "patterns", ";", "// String pattern is assumed to be path.", "foreach", "(", "$", "patterns", "as", "$", "key", "=>", "$", "pattern", ")", "{", "if", "(", "is_string", "(", "$", "pattern", ")", ")", "{", "$", "patterns", "[", "$", "key", "]", "=", "[", "'path'", "=>", "$", "pattern", "]", ";", "}", "}", "return", "$", "this", "->", "filter", "(", "function", "(", "$", "route", ")", "use", "(", "$", "patterns", ")", "{", "// If any of patterns matches - route passes.", "foreach", "(", "$", "patterns", "as", "$", "pattern", ")", "{", "if", "(", "$", "this", "->", "isRouteMatchesPattern", "(", "$", "route", ",", "$", "pattern", ")", ")", "{", "return", "true", ";", "}", "}", "// If all patterns don't match - route is filtered out.", "return", "false", ";", "}", ")", ";", "}" ]
Include routes that match patterns. @param array <array|string> $patterns @return static
[ "Include", "routes", "that", "match", "patterns", "." ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Collections/RouteCollection.php#L21-L43
asvae/laravel-api-tester
src/Collections/RouteCollection.php
RouteCollection.filterExcept
public function filterExcept($patterns = []) { if (empty($patterns)) { return $this; } $toExclude = $this->filterMatch($patterns)->keys()->toArray(); return $this->except($toExclude); }
php
public function filterExcept($patterns = []) { if (empty($patterns)) { return $this; } $toExclude = $this->filterMatch($patterns)->keys()->toArray(); return $this->except($toExclude); }
[ "public", "function", "filterExcept", "(", "$", "patterns", "=", "[", "]", ")", "{", "if", "(", "empty", "(", "$", "patterns", ")", ")", "{", "return", "$", "this", ";", "}", "$", "toExclude", "=", "$", "this", "->", "filterMatch", "(", "$", "patterns", ")", "->", "keys", "(", ")", "->", "toArray", "(", ")", ";", "return", "$", "this", "->", "except", "(", "$", "toExclude", ")", ";", "}" ]
Exclude routes that match patterns. @param array <array|string> $patterns @return static
[ "Exclude", "routes", "that", "match", "patterns", "." ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Collections/RouteCollection.php#L53-L62
asvae/laravel-api-tester
src/Entities/RequestEntity.php
RequestEntity.createExisting
public static function createExisting($data) { $newRequest = new static($data); $newRequest->setId($data['id']); $newRequest->setExists(true); return $newRequest; }
php
public static function createExisting($data) { $newRequest = new static($data); $newRequest->setId($data['id']); $newRequest->setExists(true); return $newRequest; }
[ "public", "static", "function", "createExisting", "(", "$", "data", ")", "{", "$", "newRequest", "=", "new", "static", "(", "$", "data", ")", ";", "$", "newRequest", "->", "setId", "(", "$", "data", "[", "'id'", "]", ")", ";", "$", "newRequest", "->", "setExists", "(", "true", ")", ";", "return", "$", "newRequest", ";", "}" ]
@param $data @return static
[ "@param", "$data" ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Entities/RequestEntity.php#L59-L66
asvae/laravel-api-tester
src/Repositories/RequestRepository.php
RequestRepository.persist
public function persist(RequestEntity $request) { $request->setId(str_random()); $this->requests->insert($request); }
php
public function persist(RequestEntity $request) { $request->setId(str_random()); $this->requests->insert($request); }
[ "public", "function", "persist", "(", "RequestEntity", "$", "request", ")", "{", "$", "request", "->", "setId", "(", "str_random", "(", ")", ")", ";", "$", "this", "->", "requests", "->", "insert", "(", "$", "request", ")", ";", "}" ]
@param \Asvae\ApiTester\Entities\RequestEntity $request @return mixed
[ "@param", "\\", "Asvae", "\\", "ApiTester", "\\", "Entities", "\\", "RequestEntity", "$request" ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Repositories/RequestRepository.php#L83-L87
asvae/laravel-api-tester
src/Providers/RepositoryServiceProvider.php
RepositoryServiceProvider.register
public function register() { $this->app->singleton(RouteRepositoryInterface::class, function (Container $app) { $repositories = []; foreach (config('api-tester.route_repositories') as $repository) { $repositories[] = $app->make($repository); } $routeCollection = $app->make(RouteCollection::class); return new RouteRepository($routeCollection, $repositories); }); $this->app->singleton( RequestRepositoryInterface::class, config('api-tester.request_repository') ); }
php
public function register() { $this->app->singleton(RouteRepositoryInterface::class, function (Container $app) { $repositories = []; foreach (config('api-tester.route_repositories') as $repository) { $repositories[] = $app->make($repository); } $routeCollection = $app->make(RouteCollection::class); return new RouteRepository($routeCollection, $repositories); }); $this->app->singleton( RequestRepositoryInterface::class, config('api-tester.request_repository') ); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "app", "->", "singleton", "(", "RouteRepositoryInterface", "::", "class", ",", "function", "(", "Container", "$", "app", ")", "{", "$", "repositories", "=", "[", "]", ";", "foreach", "(", "config", "(", "'api-tester.route_repositories'", ")", "as", "$", "repository", ")", "{", "$", "repositories", "[", "]", "=", "$", "app", "->", "make", "(", "$", "repository", ")", ";", "}", "$", "routeCollection", "=", "$", "app", "->", "make", "(", "RouteCollection", "::", "class", ")", ";", "return", "new", "RouteRepository", "(", "$", "routeCollection", ",", "$", "repositories", ")", ";", "}", ")", ";", "$", "this", "->", "app", "->", "singleton", "(", "RequestRepositoryInterface", "::", "class", ",", "config", "(", "'api-tester.request_repository'", ")", ")", ";", "}" ]
Register the service provider. @return void
[ "Register", "the", "service", "provider", "." ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Providers/RepositoryServiceProvider.php#L29-L46
asvae/laravel-api-tester
src/Collections/RequestCollection.php
RequestCollection.load
public function load($data) { foreach ($data as $row) { $this->put($row['id'], RequestEntity::createExisting($row)); } return $this; }
php
public function load($data) { foreach ($data as $row) { $this->put($row['id'], RequestEntity::createExisting($row)); } return $this; }
[ "public", "function", "load", "(", "$", "data", ")", "{", "foreach", "(", "$", "data", "as", "$", "row", ")", "{", "$", "this", "->", "put", "(", "$", "row", "[", "'id'", "]", ",", "RequestEntity", "::", "createExisting", "(", "$", "row", ")", ")", ";", "}", "return", "$", "this", ";", "}" ]
Load data to collection. @param $data @return static
[ "Load", "data", "to", "collection", "." ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Collections/RequestCollection.php#L48-L55
asvae/laravel-api-tester
src/Collections/RequestCollection.php
RequestCollection.onlyDiff
public function onlyDiff() { return $this->filter(function (RequestEntity $request) { return ($request->notExists() || $request->isDirty()) && $request->notMarkedToDelete(); }); }
php
public function onlyDiff() { return $this->filter(function (RequestEntity $request) { return ($request->notExists() || $request->isDirty()) && $request->notMarkedToDelete(); }); }
[ "public", "function", "onlyDiff", "(", ")", "{", "return", "$", "this", "->", "filter", "(", "function", "(", "RequestEntity", "$", "request", ")", "{", "return", "(", "$", "request", "->", "notExists", "(", ")", "||", "$", "request", "->", "isDirty", "(", ")", ")", "&&", "$", "request", "->", "notMarkedToDelete", "(", ")", ";", "}", ")", ";", "}" ]
Новые записи или измененные записи, которые не были помечены на удаление. @return static
[ "Новые", "записи", "или", "измененные", "записи", "которые", "не", "были", "помечены", "на", "удаление", "." ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Collections/RequestCollection.php#L69-L74
asvae/laravel-api-tester
src/Storages/FireBaseStorage.php
FireBaseStorage.get
public function get() { $result = $this->getFromFireBase(); $data = $this->addHeadersIfEmpty($result); return $this->makeCollection($data); }
php
public function get() { $result = $this->getFromFireBase(); $data = $this->addHeadersIfEmpty($result); return $this->makeCollection($data); }
[ "public", "function", "get", "(", ")", "{", "$", "result", "=", "$", "this", "->", "getFromFireBase", "(", ")", ";", "$", "data", "=", "$", "this", "->", "addHeadersIfEmpty", "(", "$", "result", ")", ";", "return", "$", "this", "->", "makeCollection", "(", "$", "data", ")", ";", "}" ]
Get data from resource. @return RequestCollection
[ "Get", "data", "from", "resource", "." ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Storages/FireBaseStorage.php#L49-L56
asvae/laravel-api-tester
src/Storages/FireBaseStorage.php
FireBaseStorage.put
public function put(RequestCollection $data) { $this->store($data->onlyDiff()); $this->delete($data->onlyToDelete()); }
php
public function put(RequestCollection $data) { $this->store($data->onlyDiff()); $this->delete($data->onlyToDelete()); }
[ "public", "function", "put", "(", "RequestCollection", "$", "data", ")", "{", "$", "this", "->", "store", "(", "$", "data", "->", "onlyDiff", "(", ")", ")", ";", "$", "this", "->", "delete", "(", "$", "data", "->", "onlyToDelete", "(", ")", ")", ";", "}" ]
Put data to resource. @param $data RequestCollection @return void
[ "Put", "data", "to", "resource", "." ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Storages/FireBaseStorage.php#L64-L68
asvae/laravel-api-tester
src/Http/Controllers/RequestController.php
RequestController.update
public function update(UpdateRequest $request) { $requestEntity = $this->repository->find($request->id); // TODO What's happening in here? if (!$requestEntity instanceof RequestEntity) { return response(404); } $requestEntity->update($request->all()); $this->repository->flush(); return response(['data' => $requestEntity->toArray()], 200); }
php
public function update(UpdateRequest $request) { $requestEntity = $this->repository->find($request->id); // TODO What's happening in here? if (!$requestEntity instanceof RequestEntity) { return response(404); } $requestEntity->update($request->all()); $this->repository->flush(); return response(['data' => $requestEntity->toArray()], 200); }
[ "public", "function", "update", "(", "UpdateRequest", "$", "request", ")", "{", "$", "requestEntity", "=", "$", "this", "->", "repository", "->", "find", "(", "$", "request", "->", "id", ")", ";", "// TODO What's happening in here?", "if", "(", "!", "$", "requestEntity", "instanceof", "RequestEntity", ")", "{", "return", "response", "(", "404", ")", ";", "}", "$", "requestEntity", "->", "update", "(", "$", "request", "->", "all", "(", ")", ")", ";", "$", "this", "->", "repository", "->", "flush", "(", ")", ";", "return", "response", "(", "[", "'data'", "=>", "$", "requestEntity", "->", "toArray", "(", ")", "]", ",", "200", ")", ";", "}" ]
@param \Asvae\ApiTester\Http\Requests\UpdateRequest $request @param string $request @return \Illuminate\Http\Response @internal param int $id
[ "@param", "\\", "Asvae", "\\", "ApiTester", "\\", "Http", "\\", "Requests", "\\", "UpdateRequest", "$request", "@param", "string", "$request" ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Http/Controllers/RequestController.php#L89-L102
asvae/laravel-api-tester
src/Providers/RouteServiceProvider.php
RouteServiceProvider.map
public function map(Router $router) { $router->group([ 'as' => 'api-tester.', 'prefix' => config('api-tester.route'), 'namespace' => $this->getNamespace(), 'middleware' => $this->getMiddleware(), ], function () { $this->requireRoutes(); }); }
php
public function map(Router $router) { $router->group([ 'as' => 'api-tester.', 'prefix' => config('api-tester.route'), 'namespace' => $this->getNamespace(), 'middleware' => $this->getMiddleware(), ], function () { $this->requireRoutes(); }); }
[ "public", "function", "map", "(", "Router", "$", "router", ")", "{", "$", "router", "->", "group", "(", "[", "'as'", "=>", "'api-tester.'", ",", "'prefix'", "=>", "config", "(", "'api-tester.route'", ")", ",", "'namespace'", "=>", "$", "this", "->", "getNamespace", "(", ")", ",", "'middleware'", "=>", "$", "this", "->", "getMiddleware", "(", ")", ",", "]", ",", "function", "(", ")", "{", "$", "this", "->", "requireRoutes", "(", ")", ";", "}", ")", ";", "}" ]
Define the routes for the application. @param Router $router @return void
[ "Define", "the", "routes", "for", "the", "application", "." ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Providers/RouteServiceProvider.php#L26-L36
asvae/laravel-api-tester
src/Repositories/RouteRepository.php
RouteRepository.get
public function get($match = [], $except = []) { foreach ($this->repositories as $repository) { foreach ($repository->get($match, $except) as $route) { $this->routes->push($route); } } return $this->routes; }
php
public function get($match = [], $except = []) { foreach ($this->repositories as $repository) { foreach ($repository->get($match, $except) as $route) { $this->routes->push($route); } } return $this->routes; }
[ "public", "function", "get", "(", "$", "match", "=", "[", "]", ",", "$", "except", "=", "[", "]", ")", "{", "foreach", "(", "$", "this", "->", "repositories", "as", "$", "repository", ")", "{", "foreach", "(", "$", "repository", "->", "get", "(", "$", "match", ",", "$", "except", ")", "as", "$", "route", ")", "{", "$", "this", "->", "routes", "->", "push", "(", "$", "route", ")", ";", "}", "}", "return", "$", "this", "->", "routes", ";", "}" ]
@param array $match @param array $except @return mixed
[ "@param", "array", "$match", "@param", "array", "$except" ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Repositories/RouteRepository.php#L37-L47
asvae/laravel-api-tester
src/Http/Controllers/RouteController.php
RouteController.index
public function index(RouteRepositoryInterface $repository) { $data = $repository->get( config('api-tester.include'), config('api-tester.exclude') ); return response()->json(compact('data')); }
php
public function index(RouteRepositoryInterface $repository) { $data = $repository->get( config('api-tester.include'), config('api-tester.exclude') ); return response()->json(compact('data')); }
[ "public", "function", "index", "(", "RouteRepositoryInterface", "$", "repository", ")", "{", "$", "data", "=", "$", "repository", "->", "get", "(", "config", "(", "'api-tester.include'", ")", ",", "config", "(", "'api-tester.exclude'", ")", ")", ";", "return", "response", "(", ")", "->", "json", "(", "compact", "(", "'data'", ")", ")", ";", "}" ]
Display list of all available routes. @param RouteRepositoryInterface $repository @return \Illuminate\Http\JsonResponse
[ "Display", "list", "of", "all", "available", "routes", "." ]
train
https://github.com/asvae/laravel-api-tester/blob/7fd5d86bdcfc2b8c2e898c89b41feedf0c1b5e67/src/Http/Controllers/RouteController.php#L21-L29
stefangabos/Zebra_cURL
Zebra_cURL.php
Zebra_cURL.cache
public function cache($path, $lifetime = 3600, $compress = true, $chmod = 0755) { // if caching is not explicitly disabled if ($path !== false) { // if path doesn't exist, attempt to create it if (!is_dir($path)) @mkdir($path, $chmod, true); // save cache-related properties $this->cache = array( 'path' => $path, 'lifetime' => $lifetime, 'chmod' => $chmod, 'compress' => $compress, ); // if caching is explicitly disabled, set this property to FALSE } else $this->cache = false; }
php
public function cache($path, $lifetime = 3600, $compress = true, $chmod = 0755) { // if caching is not explicitly disabled if ($path !== false) { // if path doesn't exist, attempt to create it if (!is_dir($path)) @mkdir($path, $chmod, true); // save cache-related properties $this->cache = array( 'path' => $path, 'lifetime' => $lifetime, 'chmod' => $chmod, 'compress' => $compress, ); // if caching is explicitly disabled, set this property to FALSE } else $this->cache = false; }
[ "public", "function", "cache", "(", "$", "path", ",", "$", "lifetime", "=", "3600", ",", "$", "compress", "=", "true", ",", "$", "chmod", "=", "0755", ")", "{", "// if caching is not explicitly disabled", "if", "(", "$", "path", "!==", "false", ")", "{", "// if path doesn't exist, attempt to create it", "if", "(", "!", "is_dir", "(", "$", "path", ")", ")", "@", "mkdir", "(", "$", "path", ",", "$", "chmod", ",", "true", ")", ";", "// save cache-related properties", "$", "this", "->", "cache", "=", "array", "(", "'path'", "=>", "$", "path", ",", "'lifetime'", "=>", "$", "lifetime", ",", "'chmod'", "=>", "$", "chmod", ",", "'compress'", "=>", "$", "compress", ",", ")", ";", "// if caching is explicitly disabled, set this property to FALSE", "}", "else", "$", "this", "->", "cache", "=", "false", ";", "}" ]
Use this method to enable caching of requests. <i>Note that only the actual request is cached and not associated downloads, if any!</i> <i>Caching is disabled by default!</i> <code> // the callback function to be executed for each and every // request, as soon as a request finishes // the callback function receives as argument an object with 4 properties // (info, header, body and response) function mycallback($result) { // everything went well at cURL level if ($result->response[1] == CURLE_OK) { // if server responded with code 200 (meaning that everything went well) // see http://httpstatus.es/ for a list of possible response codes if ($result->info['http_code'] == 200) { // see all the returned data print_r('<pre>'); print_r($result); // show the server's response code } else die('Server responded with code ' . $result->info['http_code']); // something went wrong // ($result still contains all data that could be gathered) } else die('cURL responded with: ' . $result->response[0]); } // include the Zebra_cURL library require 'path/to/Zebra_cURL'; // instantiate the Zebra_cURL object $curl = new Zebra_cURL(); // cache results in the "cache" folder and for 86400 seconds (24 hours) $curl->cache('cache', 86400); // let's fetch the RSS feeds of some popular tech-related websites // execute the "mycallback" function for each request, as soon as it finishes $curl->get(array( 'http://feeds.feedburner.com/alistapart/main', 'http://feeds.feedburner.com/TechCrunch', 'http://feeds.mashable.com/mashable', ), 'mycallback') </code> @param string $path Path where cache files to be stored. Setting this to FALSE will disable caching. <i>If set to a non-existing path, the library will try to create the folder and will trigger an error if, for whatever reasons, it is unable to do so. If the folder can be created, its permissions will be set to the value of $chmod</i> @param integer $lifetime (Optional) The number of seconds after which cache will be considered expired. Default is 3600 (one hour). @param boolean $compress (Optional) If set to TRUE, cache files will be {@link http://php.net/manual/en/function.gzcompress.php gzcompress}-ed so that they occupy less disk space. Default is TRUE. @param octal $chmod (Optional) The file system permissions to be set for newly created cache files. I suggest using the value "0755" (without the quotes) but, if you know what you are doing, here is how you can calculate the permission levels: - 400 Owner Read - 200 Owner Write - 100 Owner Execute - 40 Group Read - 20 Group Write - 10 Group Execute - 4 Global Read - 2 Global Write - 1 Global Execute Default is "0755" (without the quotes). @return void
[ "Use", "this", "method", "to", "enable", "caching", "of", "requests", "." ]
train
https://github.com/stefangabos/Zebra_cURL/blob/bf9f5b27ca5783cba97f51243bf1354ab18c1483/Zebra_cURL.php#L424-L443
stefangabos/Zebra_cURL
Zebra_cURL.php
Zebra_cURL.cookies
public function cookies($path) { // file does not exist if (!is_file($path)) { // attempt to create it if (!($handle = fopen($path, 'a'))) // if file could not be created, trigger an error trigger_error('File "' . $path . '" for storing cookies could not be found nor could it automatically be created! Make sure either that the path to the file points to a writable directory, or create the file yourself and make it writable', E_USER_ERROR); // if file could be create, release handle fclose($handle); } // set these options $this->option(array( CURLOPT_COOKIEJAR => $path, // for writing CURLOPT_COOKIEFILE => $path, // for reading )); }
php
public function cookies($path) { // file does not exist if (!is_file($path)) { // attempt to create it if (!($handle = fopen($path, 'a'))) // if file could not be created, trigger an error trigger_error('File "' . $path . '" for storing cookies could not be found nor could it automatically be created! Make sure either that the path to the file points to a writable directory, or create the file yourself and make it writable', E_USER_ERROR); // if file could be create, release handle fclose($handle); } // set these options $this->option(array( CURLOPT_COOKIEJAR => $path, // for writing CURLOPT_COOKIEFILE => $path, // for reading )); }
[ "public", "function", "cookies", "(", "$", "path", ")", "{", "// file does not exist", "if", "(", "!", "is_file", "(", "$", "path", ")", ")", "{", "// attempt to create it", "if", "(", "!", "(", "$", "handle", "=", "fopen", "(", "$", "path", ",", "'a'", ")", ")", ")", "// if file could not be created, trigger an error", "trigger_error", "(", "'File \"'", ".", "$", "path", ".", "'\" for storing cookies could not be found nor could it automatically be created! Make sure either that the path to the file points to a writable directory, or create the file yourself and make it writable'", ",", "E_USER_ERROR", ")", ";", "// if file could be create, release handle", "fclose", "(", "$", "handle", ")", ";", "}", "// set these options", "$", "this", "->", "option", "(", "array", "(", "CURLOPT_COOKIEJAR", "=>", "$", "path", ",", "// for writing", "CURLOPT_COOKIEFILE", "=>", "$", "path", ",", "// for reading", ")", ")", ";", "}" ]
Sets the path and name of the file to save to / retrieve cookies from. All cookie data will be stored in this file on a per-domain basis. Important when cookies need to stored/restored to maintain status/session of requests made to the same domains. This method will automatically set the <b>CURLOPT_COOKIEJAR</b> and <b>CURLOPT_COOKIEFILE</b> options. @param string $path The path to a file to save to / retrieve cookies from. If file does not exist the library will attempt to create it, and if it is unable to create it will trigger an error. @return void
[ "Sets", "the", "path", "and", "name", "of", "the", "file", "to", "save", "to", "/", "retrieve", "cookies", "from", ".", "All", "cookie", "data", "will", "be", "stored", "in", "this", "file", "on", "a", "per", "-", "domain", "basis", ".", "Important", "when", "cookies", "need", "to", "stored", "/", "restored", "to", "maintain", "status", "/", "session", "of", "requests", "made", "to", "the", "same", "domains", "." ]
train
https://github.com/stefangabos/Zebra_cURL/blob/bf9f5b27ca5783cba97f51243bf1354ab18c1483/Zebra_cURL.php#L459-L481
stefangabos/Zebra_cURL
Zebra_cURL.php
Zebra_cURL.download
public function download($urls, $path, $callback = '') { // if destination path is not a directory or is not writable, trigger an error message if (!is_dir($path) || !is_writable($path)) trigger_error('"' . $path . '" is not a valid path or is not writable', E_USER_ERROR); // normalize URLs // (transforms every allowed combination to the same type of array) $urls = $this->_prepare_urls($urls); // iterate through the list of URLs to process foreach ($urls as $values) // add each URL and associated properties to the "_requests" property $this->_requests[] = array( 'url' => $values['url'], 'path' => rtrim($path, '/\\') . '/', // merge any custom options with the default ones 'options' => (isset($values['options']) ? $values['options'] : array()) + array( CURLINFO_HEADER_OUT => 1, CURLOPT_BINARYTRANSFER => 1, CURLOPT_HEADER => 0, CURLOPT_CUSTOMREQUEST => null, CURLOPT_HTTPGET => null, CURLOPT_NOBODY => null, CURLOPT_POST => null, CURLOPT_POSTFIELDS => null, ), 'callback' => $callback, // additional arguments to pass to the callback function, if any 'arguments' => array_slice(func_get_args(), 3), ); // if we're just queuing requests for now, do not execute the next lines if ($this->_queue) return; // if we have to pause between batches of requests, process them sequentially, in batches if ($this->pause_interval > 0) $this->_process_paused(); // if we don't have to pause between batches of requests, process them all at once else $this->_process(); }
php
public function download($urls, $path, $callback = '') { // if destination path is not a directory or is not writable, trigger an error message if (!is_dir($path) || !is_writable($path)) trigger_error('"' . $path . '" is not a valid path or is not writable', E_USER_ERROR); // normalize URLs // (transforms every allowed combination to the same type of array) $urls = $this->_prepare_urls($urls); // iterate through the list of URLs to process foreach ($urls as $values) // add each URL and associated properties to the "_requests" property $this->_requests[] = array( 'url' => $values['url'], 'path' => rtrim($path, '/\\') . '/', // merge any custom options with the default ones 'options' => (isset($values['options']) ? $values['options'] : array()) + array( CURLINFO_HEADER_OUT => 1, CURLOPT_BINARYTRANSFER => 1, CURLOPT_HEADER => 0, CURLOPT_CUSTOMREQUEST => null, CURLOPT_HTTPGET => null, CURLOPT_NOBODY => null, CURLOPT_POST => null, CURLOPT_POSTFIELDS => null, ), 'callback' => $callback, // additional arguments to pass to the callback function, if any 'arguments' => array_slice(func_get_args(), 3), ); // if we're just queuing requests for now, do not execute the next lines if ($this->_queue) return; // if we have to pause between batches of requests, process them sequentially, in batches if ($this->pause_interval > 0) $this->_process_paused(); // if we don't have to pause between batches of requests, process them all at once else $this->_process(); }
[ "public", "function", "download", "(", "$", "urls", ",", "$", "path", ",", "$", "callback", "=", "''", ")", "{", "// if destination path is not a directory or is not writable, trigger an error message", "if", "(", "!", "is_dir", "(", "$", "path", ")", "||", "!", "is_writable", "(", "$", "path", ")", ")", "trigger_error", "(", "'\"'", ".", "$", "path", ".", "'\" is not a valid path or is not writable'", ",", "E_USER_ERROR", ")", ";", "// normalize URLs", "// (transforms every allowed combination to the same type of array)", "$", "urls", "=", "$", "this", "->", "_prepare_urls", "(", "$", "urls", ")", ";", "// iterate through the list of URLs to process", "foreach", "(", "$", "urls", "as", "$", "values", ")", "// add each URL and associated properties to the \"_requests\" property", "$", "this", "->", "_requests", "[", "]", "=", "array", "(", "'url'", "=>", "$", "values", "[", "'url'", "]", ",", "'path'", "=>", "rtrim", "(", "$", "path", ",", "'/\\\\'", ")", ".", "'/'", ",", "// merge any custom options with the default ones", "'options'", "=>", "(", "isset", "(", "$", "values", "[", "'options'", "]", ")", "?", "$", "values", "[", "'options'", "]", ":", "array", "(", ")", ")", "+", "array", "(", "CURLINFO_HEADER_OUT", "=>", "1", ",", "CURLOPT_BINARYTRANSFER", "=>", "1", ",", "CURLOPT_HEADER", "=>", "0", ",", "CURLOPT_CUSTOMREQUEST", "=>", "null", ",", "CURLOPT_HTTPGET", "=>", "null", ",", "CURLOPT_NOBODY", "=>", "null", ",", "CURLOPT_POST", "=>", "null", ",", "CURLOPT_POSTFIELDS", "=>", "null", ",", ")", ",", "'callback'", "=>", "$", "callback", ",", "// additional arguments to pass to the callback function, if any", "'arguments'", "=>", "array_slice", "(", "func_get_args", "(", ")", ",", "3", ")", ",", ")", ";", "// if we're just queuing requests for now, do not execute the next lines", "if", "(", "$", "this", "->", "_queue", ")", "return", ";", "// if we have to pause between batches of requests, process them sequentially, in batches", "if", "(", "$", "this", "->", "pause_interval", ">", "0", ")", "$", "this", "->", "_process_paused", "(", ")", ";", "// if we don't have to pause between batches of requests, process them all at once", "else", "$", "this", "->", "_process", "(", ")", ";", "}" ]
Downloads one or more files from one or more URLs, saves the downloaded files to the path specified by the <i>$path</i> argument, and executes the callback function specified by the <i>$callback</i> argument for each and every request, as soon as a request finishes. <samp>If the path you are downloading from refers to a file, then the file's original name will be preserved but, if you are downloading a file generated by a script (i.e. http://foo.com/bar.php?w=1200&h=800), the downloaded file's name will be random generated. Refer to the downloaded file's name in the result's "info" attribute, in the "downloaded_filename" section - see the example below.</samp> Downloads are streamed (bytes downloaded are directly written to disk) removing the unnecessary strain from your server of reading files into memory first, and then writing them to disk. This method will automatically set the following options: - <b>CURLINFO_HEADER_OUT</b> - TRUE - <b>CURLOPT_BINARYTRANSFER</b> - TRUE - <b>CURLOPT_HEADER</b> - TRUE - <b>CURLOPT_FILE</b> ...and will unset the following options: - <b>CURLOPT_CUSTOMREQUEST</b> - <b>CURLOPT_HTTPGET</b> - <b>CURLOPT_NOBODY</b> - <b>CURLOPT_POST</b> - <b>CURLOPT_POSTFIELDS</b> Files are downloaded preserving their original names, so you may want to check that if you are downloading more files having the same name! Multiple requests are processed asynchronously, in parallel, and the callback function is called for each and every request, as soon as a request finishes. The number of parallel requests to be constantly processed, at all times, can be set through the {@link threads} property. See also the {@link pause_interval} property. <i>Note that requests may not finish in the same order as initiated!</i> <code> // the callback function to be executed for each and every // request, as soon as a request finishes // the callback function receives as argument an object with 4 properties // (info, header, body and response) function mycallback($result) { // everything went well at cURL level if ($result->response[1] == CURLE_OK) { // if server responded with code 200 (meaning that everything went well) // see http://httpstatus.es/ for a list of possible response codes if ($result->info['http_code'] == 200) { // see all the returned data print_r('<pre>'); print_r($result); // get the downloaded file's path $result->info['downloaded_filename']; // show the server's response code } else die('Server responded with code ' . $result->info['http_code']); // something went wrong // ($result still contains all data that could be gathered) } else die('cURL responded with: ' . $result->response[0]); } // include the Zebra_cURL library require 'path/to/Zebra_cURL'; // instantiate the Zebra_cURL object $curl = new Zebra_cURL(); // download 2 images from 2 different websites, and // execute the "mycallback" function for each request, as soon as it finishes $curl->download(array( 'http://www.somewebsite.com/images/alpha.jpg', 'http://www.otherwebsite.com/images/omega.jpg', ), 'destination/path/', 'mycallback'); </code> @param mixed $urls Can be any of the following: <code> // a string $curl->download('http://address.com/file.foo', 'path', 'callback'); // an array, for multiple requests $curl->download(array( 'http://address1.com/file1.foo', 'http://address2.com/file2.bar', ), 'path', 'callback'); </code> If you need to set {@link option() custom options} for each request, use the following format: <code> // this can also be an array of arrays, for multiple requests $curl->download(array( // mandatory! 'url' => 'http://address.com/file.foo', // optional, used to set any cURL option // in the same way you would set with the options() method 'options' => array( CURLOPT_USERAGENT => 'Dummy scrapper 1.0', ), ), 'path', 'callback'); </code> @param string $path The path to where to save the file(s) to. If path is not pointing to a directory or is not writable, the library will trigger an error. @param mixed $callback (Optional) Callback function to be called as soon as a request finishes. May be given as a string representing the name of an existing function, or as a {@link http://php.net/manual/en/functions.anonymous.php closure}. The callback function receives as first argument <b>an object</b> with <b>4 properties</b> as described below, while any further arguments passed to the {@link download} method will be passed as extra arguments to the callback function: - <b>info</b> - an associative array containing information about the request that just finished, as returned by PHP's {@link http://php.net/manual/en/function.curl-getinfo.php curl_getinfo} function; there's also an extra entry called <i>original_url</i> because, as curl_getinfo() only returns information about the <b>last</b> request, the original URL may be lost otherwise. - <b>headers</b> - an associative array with 2 items: <ul><li><ul><li> <b>last_request</b> an array with a single entry containing the request headers generated by <i>the last request</i>; so, remember, if there are redirects involved, there will be more requests made, but only information from the last one will be available; if explicitly disabled via the {@link option} method by setting <b>CURLINFO_HEADER_OUT</b> to 0 or FALSE, this will be an empty string; </li></ul></li></ul> <ul><li><ul><li> <b>responses</b> an empty string as it is not available for this method; </li></ul></li></ul> <i>Unless disabled, each entry in the "headers" array is an associative array in the form of property => value</i> - <b>body</b> - an empty string as it is not available for this method; - <b>response</b> - the response given by the cURL library as an array with 2 entries: the first entry is the textual representation of the result's code, while second is the result's code itself; if the request was successful, these values will be <i>array(CURLE_OK, 0);</i> consult {@link http://www.php.net/manual/en/function.curl-errno.php#103128 this list} to see the possible values of this property; <samp>If the callback function returns FALSE while {@link cache} is enabled, the library will not cache the respective request, making it easy to retry failed requests without having to clear all cache.</samp> @return void
[ "Downloads", "one", "or", "more", "files", "from", "one", "or", "more", "URLs", "saves", "the", "downloaded", "files", "to", "the", "path", "specified", "by", "the", "<i", ">", "$path<", "/", "i", ">", "argument", "and", "executes", "the", "callback", "function", "specified", "by", "the", "<i", ">", "$callback<", "/", "i", ">", "argument", "for", "each", "and", "every", "request", "as", "soon", "as", "a", "request", "finishes", "." ]
train
https://github.com/stefangabos/Zebra_cURL/blob/bf9f5b27ca5783cba97f51243bf1354ab18c1483/Zebra_cURL.php#L898-L947
stefangabos/Zebra_cURL
Zebra_cURL.php
Zebra_cURL.get
public function get($urls, $callback = '') { // normalize URLs // (transforms every allowed combination to the same type of array) $urls = $this->_prepare_urls($urls); // iterate through the list of URLs to process foreach ($urls as $values) // add each URL and associated properties to the "_requests" property $this->_requests[] = array( 'url' => $values['url'], // merge any custom options with the default ones 'options' => (isset($values['options']) ? $values['options'] : array()) + array( CURLINFO_HEADER_OUT => 1, CURLOPT_HEADER => 1, CURLOPT_HTTPGET => 1, CURLOPT_NOBODY => 0, CURLOPT_BINARYTRANSFER => null, CURLOPT_CUSTOMREQUEST => null, CURLOPT_FILE => null, CURLOPT_POST => null, CURLOPT_POSTFIELDS => null, ), 'callback' => $callback, // additional arguments to pass to the callback function, if any 'arguments' => array_slice(func_get_args(), 2), ); // if we're just queuing requests for now, do not execute the next lines if ($this->_queue) return; // if we have to pause between batches of requests, process them sequentially, in batches if ($this->pause_interval > 0) $this->_process_paused(); // if we don't have to pause between batches of requests, process them all at once else $this->_process(); }
php
public function get($urls, $callback = '') { // normalize URLs // (transforms every allowed combination to the same type of array) $urls = $this->_prepare_urls($urls); // iterate through the list of URLs to process foreach ($urls as $values) // add each URL and associated properties to the "_requests" property $this->_requests[] = array( 'url' => $values['url'], // merge any custom options with the default ones 'options' => (isset($values['options']) ? $values['options'] : array()) + array( CURLINFO_HEADER_OUT => 1, CURLOPT_HEADER => 1, CURLOPT_HTTPGET => 1, CURLOPT_NOBODY => 0, CURLOPT_BINARYTRANSFER => null, CURLOPT_CUSTOMREQUEST => null, CURLOPT_FILE => null, CURLOPT_POST => null, CURLOPT_POSTFIELDS => null, ), 'callback' => $callback, // additional arguments to pass to the callback function, if any 'arguments' => array_slice(func_get_args(), 2), ); // if we're just queuing requests for now, do not execute the next lines if ($this->_queue) return; // if we have to pause between batches of requests, process them sequentially, in batches if ($this->pause_interval > 0) $this->_process_paused(); // if we don't have to pause between batches of requests, process them all at once else $this->_process(); }
[ "public", "function", "get", "(", "$", "urls", ",", "$", "callback", "=", "''", ")", "{", "// normalize URLs", "// (transforms every allowed combination to the same type of array)", "$", "urls", "=", "$", "this", "->", "_prepare_urls", "(", "$", "urls", ")", ";", "// iterate through the list of URLs to process", "foreach", "(", "$", "urls", "as", "$", "values", ")", "// add each URL and associated properties to the \"_requests\" property", "$", "this", "->", "_requests", "[", "]", "=", "array", "(", "'url'", "=>", "$", "values", "[", "'url'", "]", ",", "// merge any custom options with the default ones", "'options'", "=>", "(", "isset", "(", "$", "values", "[", "'options'", "]", ")", "?", "$", "values", "[", "'options'", "]", ":", "array", "(", ")", ")", "+", "array", "(", "CURLINFO_HEADER_OUT", "=>", "1", ",", "CURLOPT_HEADER", "=>", "1", ",", "CURLOPT_HTTPGET", "=>", "1", ",", "CURLOPT_NOBODY", "=>", "0", ",", "CURLOPT_BINARYTRANSFER", "=>", "null", ",", "CURLOPT_CUSTOMREQUEST", "=>", "null", ",", "CURLOPT_FILE", "=>", "null", ",", "CURLOPT_POST", "=>", "null", ",", "CURLOPT_POSTFIELDS", "=>", "null", ",", ")", ",", "'callback'", "=>", "$", "callback", ",", "// additional arguments to pass to the callback function, if any", "'arguments'", "=>", "array_slice", "(", "func_get_args", "(", ")", ",", "2", ")", ",", ")", ";", "// if we're just queuing requests for now, do not execute the next lines", "if", "(", "$", "this", "->", "_queue", ")", "return", ";", "// if we have to pause between batches of requests, process them sequentially, in batches", "if", "(", "$", "this", "->", "pause_interval", ">", "0", ")", "$", "this", "->", "_process_paused", "(", ")", ";", "// if we don't have to pause between batches of requests, process them all at once", "else", "$", "this", "->", "_process", "(", ")", ";", "}" ]
Performs an HTTP <b>GET</b> request to one or more URLs and executes the callback function specified by the <i>$callback</i> argument for each and every request, as soon as a request finishes. This method will automatically set the following options: - <b>CURLINFO_HEADER_OUT</b> - TRUE - <b>CURLOPT_HEADER</b> - TRUE - <b>CURLOPT_HTTPGET</b> - TRUE - <b>CURLOPT_NOBODY</b> - FALSE ...and will unset the following options: - <b>CURLOPT_BINARYTRANSFER</b> - <b>CURLOPT_CUSTOMREQUEST</b> - <b>CURLOPT_FILE</b> - <b>CURLOPT_POST</b> - <b>CURLOPT_POSTFIELDS</b> Multiple requests are processed asynchronously, in parallel, and the callback function is called for each and every request, as soon as a request finishes. The number of parallel requests to be constantly processed, at all times, can be set through the {@link threads} property. See also the {@link pause_interval} property. <i>Note that requests may not finish in the same order as initiated!</i> <code> // the callback function to be executed for each and every // request, as soon as a request finishes // the callback function receives as argument an object with 4 properties // (info, header, body and response) function mycallback($result) { // everything went well at cURL level if ($result->response[1] == CURLE_OK) { // if server responded with code 200 (meaning that everything went well) // see http://httpstatus.es/ for a list of possible response codes if ($result->info['http_code'] == 200) { // see all the returned data print_r('<pre>'); print_r($result); // show the server's response code } else die('Server responded with code ' . $result->info['http_code']); // something went wrong // ($result still contains all data that could be gathered) } else die('cURL responded with: ' . $result->response[0]); } // include the Zebra_cURL library require 'path/to/Zebra_cURL'; // instantiate the Zebra_cURL object $curl = new Zebra_cURL(); // cache results in the "cache" folder and for 3600 seconds (one hour) $curl->cache('cache', 3600); // let's fetch the RSS feeds of some popular websites // execute the "mycallback" function for each request, as soon as it finishes $curl->get(array( 'http://feeds.feedburner.com/alistapart/main', 'http://feeds.feedburner.com/TechCrunch', 'http://feeds.mashable.com/mashable', ), 'mycallback') </code> @param mixed $urls Can be any of the following: <code> // a string $curl->get('http://address.com/', 'callback'); // an array, for multiple requests $curl->get(array( 'http://address1.com/', 'http://address2.com/', ), 'callback'); </code> If you need to set {@link option() custom options} for each request, use the following format: <code> // this can also be an array of arrays, for multiple requests $curl->get(array( // mandatory! 'url' => 'http://address.com/', // optional, used to set any cURL option // in the same way you would set with the options() method 'options' => array( CURLOPT_USERAGENT => 'Dummy scrapper 1.0', ), ), 'callback'); </code> @param mixed $callback (Optional) Callback function to be called as soon as a request finishes. May be given as a string representing the name of an existing function, or as a {@link http://php.net/manual/en/functions.anonymous.php closure}. The callback function receives as first argument <b>an object</b> with <b>4 properties</b> as described below, while any further arguments passed to the {@link get} method will be passed as extra arguments to the callback function: - <b>info</b> - an associative array containing information about the request that just finished, as returned by PHP's {@link http://php.net/manual/en/function.curl-getinfo.php curl_getinfo} function; - <b>headers</b> - an associative array with 2 items: <ul><li><ul><li> <b>last_request</b> an array with a single entry containing the request headers generated by <i>the last request</i>; so, remember, if there are redirects involved, there will be more requests made, but only information from the last one will be available; if explicitly disabled via the {@link option} method by setting <b>CURLINFO_HEADER_OUT</b> to 0 or FALSE, this will be an empty string; </li></ul></li></ul> <ul><li><ul><li> <b>responses</b> an empty string as it is not available for this method; </li></ul></li></ul> <i>Unless disabled, each entry in the "headers" array is an associative array in the form of property => value</i> - <b>body</b> - the response of the request (the content of the page at the URL). Unless disabled via the {@link __construct() constructor}, all applicable characters will be converted to HTML entities via PHP's {@link http://php.net/manual/en/function.htmlentities.php htmlentities} function, so remember to use PHP's {@link http://www.php.net/manual/en/function.html-entity-decode.php html_entity_decode} function to do reverse this, if it's the case; - <b>response</b> - the response given by the cURL library as an array with 2 entries: the first entry is the textual representation of the result's code, while second is the result's code itself; if the request was successful, these values will be <i>array(CURLE_OK, 0);</i> consult {@link http://www.php.net/manual/en/function.curl-errno.php#103128 this list} to see the possible values of this property; <samp>If the callback function returns FALSE while {@link cache} is enabled, the library will not cache the respective request, making it easy to retry failed requests without having to clear all cache.</samp> @return void
[ "Performs", "an", "HTTP", "<b", ">", "GET<", "/", "b", ">", "request", "to", "one", "or", "more", "URLs", "and", "executes", "the", "callback", "function", "specified", "by", "the", "<i", ">", "$callback<", "/", "i", ">", "argument", "for", "each", "and", "every", "request", "as", "soon", "as", "a", "request", "finishes", "." ]
train
https://github.com/stefangabos/Zebra_cURL/blob/bf9f5b27ca5783cba97f51243bf1354ab18c1483/Zebra_cURL.php#L1357-L1402
stefangabos/Zebra_cURL
Zebra_cURL.php
Zebra_cURL.http_authentication
public function http_authentication($username = '', $password = '', $type = CURLAUTH_ANY) { // set the required options $this->option(array( CURLOPT_HTTPAUTH => ($username == '' && $password == '' ? null : $type), CURLOPT_USERPWD => ($username == '' && $password == '' ? null : ($username . ':' . $password)), )); }
php
public function http_authentication($username = '', $password = '', $type = CURLAUTH_ANY) { // set the required options $this->option(array( CURLOPT_HTTPAUTH => ($username == '' && $password == '' ? null : $type), CURLOPT_USERPWD => ($username == '' && $password == '' ? null : ($username . ':' . $password)), )); }
[ "public", "function", "http_authentication", "(", "$", "username", "=", "''", ",", "$", "password", "=", "''", ",", "$", "type", "=", "CURLAUTH_ANY", ")", "{", "// set the required options", "$", "this", "->", "option", "(", "array", "(", "CURLOPT_HTTPAUTH", "=>", "(", "$", "username", "==", "''", "&&", "$", "password", "==", "''", "?", "null", ":", "$", "type", ")", ",", "CURLOPT_USERPWD", "=>", "(", "$", "username", "==", "''", "&&", "$", "password", "==", "''", "?", "null", ":", "(", "$", "username", ".", "':'", ".", "$", "password", ")", ")", ",", ")", ")", ";", "}" ]
Use this method to make requests to pages that require prior HTTP authentication. <code> // the callback function to be executed for each and every // request, as soon as a request finishes // the callback function receives as argument an object with 4 properties // (info, header, body and response) function mycallback($result) { // everything went well at cURL level if ($result->response[1] == CURLE_OK) { // if server responded with code 200 (meaning that everything went well) // see http://httpstatus.es/ for a list of possible response codes if ($result->info['http_code'] == 200) { // see all the returned data print_r('<pre>'); print_r($result); // show the server's response code } else die('Server responded with code ' . $result->info['http_code']); // something went wrong // ($result still contains all data that could be gathered) } else die('cURL responded with: ' . $result->response[0]); } // include the Zebra_cURL library require 'path/to/Zebra_cURL'; // instantiate the Zebra_cURL object $curl = new Zebra_cURL(); // prepare user name and password $curl->http_authentication('username', 'password'); // get content from a page that requires prior HTTP authentication $curl->get('http://www.some-page-requiring-prior-http-authentication.com', 'mycallback'); </code> If you have to unset previously set values use <code> $curl->http_authentication(); </code> @param string $username User name to be used for authentication. @param string $password Password to be used for authentication. @param string $type (Optional) The HTTP authentication method(s) to use. The options are: - <b>CURLAUTH_BASIC</b> - <b>CURLAUTH_DIGEST</b> - <b>CURLAUTH_GSSNEGOTIATE</b> - <b>CURLAUTH_NTLM</b> - <b>CURLAUTH_ANY</b> - CU<b>RLAUTH_ANYSAFE</b> The bitwise | (or) operator can be used to combine more than one method. If this is done, cURL will poll the server to see what methods it supports and pick the best one. <b>CURLAUTH_ANY</b> is an alias for <b>CURLAUTH_BASIC</b> | <b>CURLAUTH_DIGEST</b> | <b>CURLAUTH_GSSNEGOTIATE</b> | <b>CURLAUTH_NTLM</b>. <b>CURLAUTH_ANYSAFE</b> is an alias for <b>CURLAUTH_DIGEST</b> | <b>CURLAUTH_GSSNEGOTIATE</b> | <b>CURLAUTH_NTLM</b>. Default is <b>CURLAUTH_ANY</b>. @return void
[ "Use", "this", "method", "to", "make", "requests", "to", "pages", "that", "require", "prior", "HTTP", "authentication", "." ]
train
https://github.com/stefangabos/Zebra_cURL/blob/bf9f5b27ca5783cba97f51243bf1354ab18c1483/Zebra_cURL.php#L1670-L1678
stefangabos/Zebra_cURL
Zebra_cURL.php
Zebra_cURL.option
public function option($option, $value = '') { // if $options is given as an array if (is_array($option)) // iterate through each of the values foreach ($option as $name => $value) // if we need to "unset" an option, unset it if (is_null($value)) unset($this->options[$name]); // set the value for the option otherwise else $this->options[$name] = $value; // if option is not given as an array, // if we need to "unset" an option, unset it elseif (is_null($value)) unset($this->options[$option]); // set the value for the option otherwise else $this->options[$option] = $value; }
php
public function option($option, $value = '') { // if $options is given as an array if (is_array($option)) // iterate through each of the values foreach ($option as $name => $value) // if we need to "unset" an option, unset it if (is_null($value)) unset($this->options[$name]); // set the value for the option otherwise else $this->options[$name] = $value; // if option is not given as an array, // if we need to "unset" an option, unset it elseif (is_null($value)) unset($this->options[$option]); // set the value for the option otherwise else $this->options[$option] = $value; }
[ "public", "function", "option", "(", "$", "option", ",", "$", "value", "=", "''", ")", "{", "// if $options is given as an array", "if", "(", "is_array", "(", "$", "option", ")", ")", "// iterate through each of the values", "foreach", "(", "$", "option", "as", "$", "name", "=>", "$", "value", ")", "// if we need to \"unset\" an option, unset it", "if", "(", "is_null", "(", "$", "value", ")", ")", "unset", "(", "$", "this", "->", "options", "[", "$", "name", "]", ")", ";", "// set the value for the option otherwise", "else", "$", "this", "->", "options", "[", "$", "name", "]", "=", "$", "value", ";", "// if option is not given as an array,", "// if we need to \"unset\" an option, unset it", "elseif", "(", "is_null", "(", "$", "value", ")", ")", "unset", "(", "$", "this", "->", "options", "[", "$", "option", "]", ")", ";", "// set the value for the option otherwise", "else", "$", "this", "->", "options", "[", "$", "option", "]", "=", "$", "value", ";", "}" ]
Allows you to set one or more {@link http://php.net/manual/en/function.curl-setopt.php cURL options}. <code> // include the Zebra_cURL library require 'path/to/Zebra_cURL'; // instantiate the Zebra_cURL object $curl = new Zebra_cURL(); // setting a single option $curl->option(CURLOPT_CONNECTTIMEOUT, 10); // setting multiple options at once $curl->option(array( CURLOPT_TIMEOUT => 10, CURLOPT_CONNECTTIMEOUT => 10, )); // make a request here... </code> @param mixed $option A single option for which to set a value, or an associative array in the form of <i>option</i> => <i>value</i> (in case of an array, the <i>$value</i> argument will be disregarded). <i>Setting a value to</i> <b>null</b> <i>will "unset" that option.</i> @param mixed $value (Optional) If the <i>$option</i> argument is not an array, then this argument represents the value to be set for the respective option. If the <i>$option</i> argument is an array, then the value of this argument will be ignored. <i>Setting a value to</i> <b>null</b> <i>will "unset" that option.</i> @return void
[ "Allows", "you", "to", "set", "one", "or", "more", "{", "@link", "http", ":", "//", "php", ".", "net", "/", "manual", "/", "en", "/", "function", ".", "curl", "-", "setopt", ".", "php", "cURL", "options", "}", "." ]
train
https://github.com/stefangabos/Zebra_cURL/blob/bf9f5b27ca5783cba97f51243bf1354ab18c1483/Zebra_cURL.php#L1717-L1738
stefangabos/Zebra_cURL
Zebra_cURL.php
Zebra_cURL.proxy
public function proxy($proxy, $port = 80, $username = '', $password = '') { // if not disabled if ($proxy) { // set the required options $this->option(array( CURLOPT_HTTPPROXYTUNNEL => 1, CURLOPT_PROXY => $proxy, CURLOPT_PROXYPORT => $port, )); // if a username is also specified if ($username != '') // set authentication values $this->option(CURLOPT_PROXYUSERPWD, $username . ':' . $password); // if disabled } else // unset proxy-related options $this->option(array( CURLOPT_HTTPPROXYTUNNEL => null, CURLOPT_PROXY => null, CURLOPT_PROXYPORT => null, )); }
php
public function proxy($proxy, $port = 80, $username = '', $password = '') { // if not disabled if ($proxy) { // set the required options $this->option(array( CURLOPT_HTTPPROXYTUNNEL => 1, CURLOPT_PROXY => $proxy, CURLOPT_PROXYPORT => $port, )); // if a username is also specified if ($username != '') // set authentication values $this->option(CURLOPT_PROXYUSERPWD, $username . ':' . $password); // if disabled } else // unset proxy-related options $this->option(array( CURLOPT_HTTPPROXYTUNNEL => null, CURLOPT_PROXY => null, CURLOPT_PROXYPORT => null, )); }
[ "public", "function", "proxy", "(", "$", "proxy", ",", "$", "port", "=", "80", ",", "$", "username", "=", "''", ",", "$", "password", "=", "''", ")", "{", "// if not disabled", "if", "(", "$", "proxy", ")", "{", "// set the required options", "$", "this", "->", "option", "(", "array", "(", "CURLOPT_HTTPPROXYTUNNEL", "=>", "1", ",", "CURLOPT_PROXY", "=>", "$", "proxy", ",", "CURLOPT_PROXYPORT", "=>", "$", "port", ",", ")", ")", ";", "// if a username is also specified", "if", "(", "$", "username", "!=", "''", ")", "// set authentication values", "$", "this", "->", "option", "(", "CURLOPT_PROXYUSERPWD", ",", "$", "username", ".", "':'", ".", "$", "password", ")", ";", "// if disabled", "}", "else", "// unset proxy-related options", "$", "this", "->", "option", "(", "array", "(", "CURLOPT_HTTPPROXYTUNNEL", "=>", "null", ",", "CURLOPT_PROXY", "=>", "null", ",", "CURLOPT_PROXYPORT", "=>", "null", ",", ")", ")", ";", "}" ]
Instruct the library to tunnel all requests through a proxy server. <code> // the callback function to be executed for each and every // request, as soon as a request finishes function mycallback($result) { // everything went well at cURL level if ($result->response[1] == CURLE_OK) { // if server responded with code 200 (meaning that everything went well) // see http://httpstatus.es/ for a list of possible response codes if ($result->info['http_code'] == 200) { // see all the returned data print_r('<pre>'); print_r($result); // show the server's response code } else die('Server responded with code ' . $result->info['http_code']); // something went wrong // ($result still contains all data that could be gathered) } else die('cURL responded with: ' . $result->response[0]); } // include the Zebra_cURL library require 'path/to/Zebra_cURL'; // instantiate the class $curl = new Zebra_cURL(); // connect to a proxy server // (that's a random one i got from http://www.hidemyass.com/proxy-list/) $curl->proxy('187.63.32.250', '3128'); // fetch a page $curl->get('http://www.somewebsite.com/', 'mycallback'); </code> @param string $proxy The HTTP proxy to tunnel requests through. Can be an URL or an IP address. <i>This option can also be set using the {@link option} method and setting </i> <b>CURLOPT_PROXY</b> <i> option to the desired value</i>. Setting this argument to FALSE will "unset" all the proxy-related options. @param string $port (Optional) The port number of the proxy to connect to. Default is 80. <i>This option can also be set using the {@link option} method and setting </i> <b>CURLOPT_PROXYPORT</b> <i> option to the desired value</i>. @param string $username (Optional) The username to be used for the connection to the proxy (if required by the proxy) Default is "" (an empty string) <i>The username and the password can also be set using the {@link option} method and setting </i> <b>CURLOPT_PROXYUSERPWD</b> <i> option to the desired value formatted like </i> <b>[username]:[password]</b>. . @param string $password (Optional) The password to be used for the connection to the proxy (if required by the proxy) Default is "" (an empty string) <i>The username and the password can also be set using the {@link option} method and setting </i> <b>CURLOPT_PROXYUSERPWD</b> <i> option to the desired value formatted like </i> <b>[username]:[password]</b>. . @return void
[ "Instruct", "the", "library", "to", "tunnel", "all", "requests", "through", "a", "proxy", "server", "." ]
train
https://github.com/stefangabos/Zebra_cURL/blob/bf9f5b27ca5783cba97f51243bf1354ab18c1483/Zebra_cURL.php#L2083-L2111
stefangabos/Zebra_cURL
Zebra_cURL.php
Zebra_cURL.scrap
public function scrap($url, $body_only = true) { // this method requires the $url argument to be a string if (is_array($url)) trigger_error('URL must be a string', E_USER_ERROR); // make the request $this->get($url, function($result) { // store result in this private property of the library $this->_scrap_result = $result; }); // return result return $body_only ? $this->_scrap_result->body : $this->_scrap_result; }
php
public function scrap($url, $body_only = true) { // this method requires the $url argument to be a string if (is_array($url)) trigger_error('URL must be a string', E_USER_ERROR); // make the request $this->get($url, function($result) { // store result in this private property of the library $this->_scrap_result = $result; }); // return result return $body_only ? $this->_scrap_result->body : $this->_scrap_result; }
[ "public", "function", "scrap", "(", "$", "url", ",", "$", "body_only", "=", "true", ")", "{", "// this method requires the $url argument to be a string", "if", "(", "is_array", "(", "$", "url", ")", ")", "trigger_error", "(", "'URL must be a string'", ",", "E_USER_ERROR", ")", ";", "// make the request", "$", "this", "->", "get", "(", "$", "url", ",", "function", "(", "$", "result", ")", "{", "// store result in this private property of the library", "$", "this", "->", "_scrap_result", "=", "$", "result", ";", "}", ")", ";", "// return result", "return", "$", "body_only", "?", "$", "this", "->", "_scrap_result", "->", "body", ":", "$", "this", "->", "_scrap_result", ";", "}" ]
A shorthand for making <b>a single</b> {@link get} request without the need of a callback function <code> // include the Zebra_cURL library require 'path/to/Zebra_cURL'; // instantiate the class $curl = new Zebra_cURL(); // get page's content only $content = $curl->scrap('https://www.somewebsite.com/'); // print that to screen echo $content; // get everything we can about the page $content = $curl->scrap('https://www.somewebsite.com/', false); // print that to screen print_r('<pre>'); print_r($content); </code> @param string $url An URL to fetch. <samp>Note that this method supports a single URL. For processing multiple URLs at once, see the {@link get() get} method.</samp> @param boolean $body_only (Optional) When set to TRUE, will instruct the method to return <i>only</i> the page's content, without info, headers, responses, etc. When set to FALSE, will instruct the method to return everything it can about the scrapped page, as an object with properties as described for the <i>$callback</i> argument of the {@link get} method. Default is TRUE. @since 1.3.3 @return mixed Returns the scrapped page's content, when <i>$body_only</i> is set to TRUE, or an object with properties as described for the <i>$callback</i> argument of the {@link get} method.
[ "A", "shorthand", "for", "making", "<b", ">", "a", "single<", "/", "b", ">", "{", "@link", "get", "}", "request", "without", "the", "need", "of", "a", "callback", "function" ]
train
https://github.com/stefangabos/Zebra_cURL/blob/bf9f5b27ca5783cba97f51243bf1354ab18c1483/Zebra_cURL.php#L2495-L2511
stefangabos/Zebra_cURL
Zebra_cURL.php
Zebra_cURL.ssl
public function ssl($verify_peer = true, $verify_host = 2, $file = false, $path = false) { // set default options $this->option(array( CURLOPT_SSL_VERIFYPEER => $verify_peer, CURLOPT_SSL_VERIFYHOST => $verify_host, )); // if a path to a file holding one or more certificates to verify the peer with was given if ($file !== false) // if file could be found, use it if (is_file($file)) $this->option(CURLOPT_CAINFO, $file); // if file was not found, trigger an error else trigger_error('File "' . $file . '", holding one or more certificates to verify the peer with, was not found', E_USER_ERROR); // if a directory holding multiple CA certificates was given if ($path !== false) // if folder could be found, use it if (is_dir($path)) $this->option(CURLOPT_CAPATH, $path); // if folder was not found, trigger an error else trigger_error('Directory "' . $path . '", holding one or more CA certificates to verify the peer with, was not found', E_USER_ERROR); }
php
public function ssl($verify_peer = true, $verify_host = 2, $file = false, $path = false) { // set default options $this->option(array( CURLOPT_SSL_VERIFYPEER => $verify_peer, CURLOPT_SSL_VERIFYHOST => $verify_host, )); // if a path to a file holding one or more certificates to verify the peer with was given if ($file !== false) // if file could be found, use it if (is_file($file)) $this->option(CURLOPT_CAINFO, $file); // if file was not found, trigger an error else trigger_error('File "' . $file . '", holding one or more certificates to verify the peer with, was not found', E_USER_ERROR); // if a directory holding multiple CA certificates was given if ($path !== false) // if folder could be found, use it if (is_dir($path)) $this->option(CURLOPT_CAPATH, $path); // if folder was not found, trigger an error else trigger_error('Directory "' . $path . '", holding one or more CA certificates to verify the peer with, was not found', E_USER_ERROR); }
[ "public", "function", "ssl", "(", "$", "verify_peer", "=", "true", ",", "$", "verify_host", "=", "2", ",", "$", "file", "=", "false", ",", "$", "path", "=", "false", ")", "{", "// set default options", "$", "this", "->", "option", "(", "array", "(", "CURLOPT_SSL_VERIFYPEER", "=>", "$", "verify_peer", ",", "CURLOPT_SSL_VERIFYHOST", "=>", "$", "verify_host", ",", ")", ")", ";", "// if a path to a file holding one or more certificates to verify the peer with was given", "if", "(", "$", "file", "!==", "false", ")", "// if file could be found, use it", "if", "(", "is_file", "(", "$", "file", ")", ")", "$", "this", "->", "option", "(", "CURLOPT_CAINFO", ",", "$", "file", ")", ";", "// if file was not found, trigger an error", "else", "trigger_error", "(", "'File \"'", ".", "$", "file", ".", "'\", holding one or more certificates to verify the peer with, was not found'", ",", "E_USER_ERROR", ")", ";", "// if a directory holding multiple CA certificates was given", "if", "(", "$", "path", "!==", "false", ")", "// if folder could be found, use it", "if", "(", "is_dir", "(", "$", "path", ")", ")", "$", "this", "->", "option", "(", "CURLOPT_CAPATH", ",", "$", "path", ")", ";", "// if folder was not found, trigger an error", "else", "trigger_error", "(", "'Directory \"'", ".", "$", "path", ".", "'\", holding one or more CA certificates to verify the peer with, was not found'", ",", "E_USER_ERROR", ")", ";", "}" ]
Requests made to HTTPS servers sometimes require additional configuration, depending on the server. Most of the times {@link __construct() the defaults} set by the library will get you through, but if defaults are not working, you can set specific options using this method. <code> // include the Zebra_cURL library require 'path/to/Zebra_cURL'; // instantiate the class $curl = new Zebra_cURL(); // instruct the library to skip verifying peer's SSL certificate // (ignored if request is not made through HTTPS) $curl->ssl(false); // fetch a page $curl->get('https://www.somewebsite.com/', function($result) { print_r("<pre>"); print_r($result); }); </code> @param boolean $verify_peer (Optional) Should the peer's certificate be verified by cURL? Default is TRUE. <i>This option can also be set using the {@link option} method and setting </i> <b>CURLOPT_SSL_VERIFYPEER</b> <i> option to the desired value</i>. When you are communicating with an HTTPS site (or any other protocol that uses TLS), it will, by default, verify that the server is signed by a trusted Certificate Authority (CA) and it will most likely fail. When it does fail, instead of disabling this check, better {@link https://curl.haxx.se/docs/caextract.html download a bundle from Mozilla} and reference it via the <i>$file</i> argument below. @param integer $verify_host (Optional) Specifies whether or not to check the existence of a common name in the SSL peer certificate and that it matches with the provided hostname. - 1 to check the existence of a common name in the SSL peer certificate; - 2 to check the existence of a common name and also verify that it matches the hostname provided; in production environments the value of this option should be kept at 2; Default is 2 <samp>Support for value 1 removed in cURL 7.28.1</samp> <i>This option can also be set using the {@link option} method and setting </i> <b>CURLOPT_SSL_VERIFYHOST</b> <i> option to the desired value</i>. @param mixed $file (Optional) An absolute path to a file holding one or more certificates to verify the peer with. This only makes sense if <b>CURLOPT_SSL_VERIFYPEER</b> is set to TRUE. Default is FALSE. <i>This option can also be set using the {@link option} method and setting </i> <b>CURLOPT_CAINFO</b> <i> option to the desired value</i>. @param mixed $path (Optional) An absolute path to a directory that holds multiple CA certificates. This only makes sense if <b>CURLOPT_SSL_VERIFYPEER</b> is set to TRUE. Default is FALSE. <i>This option can also be set using the {@link option} method and setting </i> <b>CURLOPT_CAPATH</b> <i> option to the desired value</i>. @return void
[ "Requests", "made", "to", "HTTPS", "servers", "sometimes", "require", "additional", "configuration", "depending", "on", "the", "server", ".", "Most", "of", "the", "times", "{", "@link", "__construct", "()", "the", "defaults", "}", "set", "by", "the", "library", "will", "get", "you", "through", "but", "if", "defaults", "are", "not", "working", "you", "can", "set", "specific", "options", "using", "this", "method", "." ]
train
https://github.com/stefangabos/Zebra_cURL/blob/bf9f5b27ca5783cba97f51243bf1354ab18c1483/Zebra_cURL.php#L2584-L2610
stefangabos/Zebra_cURL
Zebra_cURL.php
Zebra_cURL.start
public function start() { // indicate the library that it should execute queued requests $this->_queue = false; // if we have to pause between batches of requests, process them sequentially, in batches if ($this->pause_interval > 0) $this->_process_paused(); // if we don't have to pause between batches of requests, process them all at once else $this->_process(); }
php
public function start() { // indicate the library that it should execute queued requests $this->_queue = false; // if we have to pause between batches of requests, process them sequentially, in batches if ($this->pause_interval > 0) $this->_process_paused(); // if we don't have to pause between batches of requests, process them all at once else $this->_process(); }
[ "public", "function", "start", "(", ")", "{", "// indicate the library that it should execute queued requests", "$", "this", "->", "_queue", "=", "false", ";", "// if we have to pause between batches of requests, process them sequentially, in batches", "if", "(", "$", "this", "->", "pause_interval", ">", "0", ")", "$", "this", "->", "_process_paused", "(", ")", ";", "// if we don't have to pause between batches of requests, process them all at once", "else", "$", "this", "->", "_process", "(", ")", ";", "}" ]
Executes queued requests. See {@link queue} method for more information. @since 1.3.0 @return void
[ "Executes", "queued", "requests", "." ]
train
https://github.com/stefangabos/Zebra_cURL/blob/bf9f5b27ca5783cba97f51243bf1354ab18c1483/Zebra_cURL.php#L2621-L2632
stefangabos/Zebra_cURL
Zebra_cURL.php
Zebra_cURL._debug
private function _debug() { $result = ''; // iterate through the defined constants foreach(get_defined_constants() as $name => $number) // iterate through the set options foreach ($this->options as $index => $value) // if this is a curl-related constant and it is one of the options that are set, add it to the result if (substr($name, 0, 7) == 'CURLOPT' && $number == $index) $result .= str_pad($index, 5, ' ', STR_PAD_LEFT) . ' ' . $name . ' => ' . var_export($value, true) . '<br>'; // return the result return $result; }
php
private function _debug() { $result = ''; // iterate through the defined constants foreach(get_defined_constants() as $name => $number) // iterate through the set options foreach ($this->options as $index => $value) // if this is a curl-related constant and it is one of the options that are set, add it to the result if (substr($name, 0, 7) == 'CURLOPT' && $number == $index) $result .= str_pad($index, 5, ' ', STR_PAD_LEFT) . ' ' . $name . ' => ' . var_export($value, true) . '<br>'; // return the result return $result; }
[ "private", "function", "_debug", "(", ")", "{", "$", "result", "=", "''", ";", "// iterate through the defined constants", "foreach", "(", "get_defined_constants", "(", ")", "as", "$", "name", "=>", "$", "number", ")", "// iterate through the set options", "foreach", "(", "$", "this", "->", "options", "as", "$", "index", "=>", "$", "value", ")", "// if this is a curl-related constant and it is one of the options that are set, add it to the result", "if", "(", "substr", "(", "$", "name", ",", "0", ",", "7", ")", "==", "'CURLOPT'", "&&", "$", "number", "==", "$", "index", ")", "$", "result", ".=", "str_pad", "(", "$", "index", ",", "5", ",", "' '", ",", "STR_PAD_LEFT", ")", ".", "' '", ".", "$", "name", ".", "' => '", ".", "var_export", "(", "$", "value", ",", "true", ")", ".", "'<br>'", ";", "// return the result", "return", "$", "result", ";", "}" ]
Returns the currently set options in "human-readable" format. @return string Returns the set options in "human-readable" format. @access private
[ "Returns", "the", "currently", "set", "options", "in", "human", "-", "readable", "format", "." ]
train
https://github.com/stefangabos/Zebra_cURL/blob/bf9f5b27ca5783cba97f51243bf1354ab18c1483/Zebra_cURL.php#L2641-L2657
stefangabos/Zebra_cURL
Zebra_cURL.php
Zebra_cURL._get_cache_file_name
private function _get_cache_file_name($request) { // iterate through the options associated with the request foreach ($request['options'] as $key => $value) // ...and remove null or empty values if (is_null($value) || $value == '') unset($request['options'][$key]); // remove some entries associated with the request // callback, arguments and the associated file handler (where it is the case) are not needed $request = array_diff_key($request, array('callback' => '', 'arguments' => '', 'file_handler' => '')); // return the path and name of the file name associated with the request return rtrim($this->cache['path'], '/') . '/' . md5(serialize($request)); }
php
private function _get_cache_file_name($request) { // iterate through the options associated with the request foreach ($request['options'] as $key => $value) // ...and remove null or empty values if (is_null($value) || $value == '') unset($request['options'][$key]); // remove some entries associated with the request // callback, arguments and the associated file handler (where it is the case) are not needed $request = array_diff_key($request, array('callback' => '', 'arguments' => '', 'file_handler' => '')); // return the path and name of the file name associated with the request return rtrim($this->cache['path'], '/') . '/' . md5(serialize($request)); }
[ "private", "function", "_get_cache_file_name", "(", "$", "request", ")", "{", "// iterate through the options associated with the request", "foreach", "(", "$", "request", "[", "'options'", "]", "as", "$", "key", "=>", "$", "value", ")", "// ...and remove null or empty values", "if", "(", "is_null", "(", "$", "value", ")", "||", "$", "value", "==", "''", ")", "unset", "(", "$", "request", "[", "'options'", "]", "[", "$", "key", "]", ")", ";", "// remove some entries associated with the request", "// callback, arguments and the associated file handler (where it is the case) are not needed", "$", "request", "=", "array_diff_key", "(", "$", "request", ",", "array", "(", "'callback'", "=>", "''", ",", "'arguments'", "=>", "''", ",", "'file_handler'", "=>", "''", ")", ")", ";", "// return the path and name of the file name associated with the request", "return", "rtrim", "(", "$", "this", "->", "cache", "[", "'path'", "]", ",", "'/'", ")", ".", "'/'", ".", "md5", "(", "serialize", "(", "$", "request", ")", ")", ";", "}" ]
Returns the cache file name associated with a specific request. @return string Returns the set options in "human-readable" format. @access private
[ "Returns", "the", "cache", "file", "name", "associated", "with", "a", "specific", "request", "." ]
train
https://github.com/stefangabos/Zebra_cURL/blob/bf9f5b27ca5783cba97f51243bf1354ab18c1483/Zebra_cURL.php#L2666-L2681
stefangabos/Zebra_cURL
Zebra_cURL.php
Zebra_cURL._parse_headers
private function _parse_headers($headers) { $result = array(); // if we have nothing to work with if ($headers != '') { // split multiple headers by blank lines $headers = preg_split('/^\s*$/m', trim($headers)); // iterate through the headers foreach($headers as $index => $header) { $arguments_count = func_num_args(); // get all the lines in the header // lines in headers look like [name] : [value] // also, the first line, the status, does not have a name, so we add the name now preg_match_all('/^(.*?)\:\s(.*)$/m', ($arguments_count == 2 ? 'Request Method: ' : 'Status: ') . trim($header), $matches); // save results foreach ($matches[0] as $key => $value) $result[$index][$matches[1][$key]] = trim($matches[2][$key]); } } // return headers as an array return $result; }
php
private function _parse_headers($headers) { $result = array(); // if we have nothing to work with if ($headers != '') { // split multiple headers by blank lines $headers = preg_split('/^\s*$/m', trim($headers)); // iterate through the headers foreach($headers as $index => $header) { $arguments_count = func_num_args(); // get all the lines in the header // lines in headers look like [name] : [value] // also, the first line, the status, does not have a name, so we add the name now preg_match_all('/^(.*?)\:\s(.*)$/m', ($arguments_count == 2 ? 'Request Method: ' : 'Status: ') . trim($header), $matches); // save results foreach ($matches[0] as $key => $value) $result[$index][$matches[1][$key]] = trim($matches[2][$key]); } } // return headers as an array return $result; }
[ "private", "function", "_parse_headers", "(", "$", "headers", ")", "{", "$", "result", "=", "array", "(", ")", ";", "// if we have nothing to work with", "if", "(", "$", "headers", "!=", "''", ")", "{", "// split multiple headers by blank lines", "$", "headers", "=", "preg_split", "(", "'/^\\s*$/m'", ",", "trim", "(", "$", "headers", ")", ")", ";", "// iterate through the headers", "foreach", "(", "$", "headers", "as", "$", "index", "=>", "$", "header", ")", "{", "$", "arguments_count", "=", "func_num_args", "(", ")", ";", "// get all the lines in the header", "// lines in headers look like [name] : [value]", "// also, the first line, the status, does not have a name, so we add the name now", "preg_match_all", "(", "'/^(.*?)\\:\\s(.*)$/m'", ",", "(", "$", "arguments_count", "==", "2", "?", "'Request Method: '", ":", "'Status: '", ")", ".", "trim", "(", "$", "header", ")", ",", "$", "matches", ")", ";", "// save results", "foreach", "(", "$", "matches", "[", "0", "]", "as", "$", "key", "=>", "$", "value", ")", "$", "result", "[", "$", "index", "]", "[", "$", "matches", "[", "1", "]", "[", "$", "key", "]", "]", "=", "trim", "(", "$", "matches", "[", "2", "]", "[", "$", "key", "]", ")", ";", "}", "}", "// return headers as an array", "return", "$", "result", ";", "}" ]
Parse response headers. It parses a string containing one or more HTTP headers and returns an array of headers where each entry also contains an associative array of <i>name</i> => <i>value</i> for each row of data in the respective header. @param string $headers A string containing one or more HTTP headers, where multiple headers are separated by a blank line. @return mixed Returns an array of headers where each entry also contains an associative array of <i>name</i> => <i>value</i> for each row of data in the respective header. If CURLOPT_HEADER is set to FALSE or 0, this method will return an empty string. @access private
[ "Parse", "response", "headers", "." ]
train
https://github.com/stefangabos/Zebra_cURL/blob/bf9f5b27ca5783cba97f51243bf1354ab18c1483/Zebra_cURL.php#L2699-L2731
stefangabos/Zebra_cURL
Zebra_cURL.php
Zebra_cURL._prepare_urls
private function _prepare_urls($urls) { // if $urls is *one* associative array containing one of "url", "options" and "data" entries if (is_array($urls) && !empty(array_intersect(array('url', 'options', 'data'), array_keys($urls)))) { // since "url" is mandatory, stop if not present if (!isset($urls['url'])) trigger_error('<strong>url</strong> key is missing from argument', E_USER_ERROR); // return as an array of arrays return array($urls); // if $urls is an array } elseif (is_array($urls)) { $result = array(); // iterate over the entries in the array foreach ($urls as $key => $values) { // if key is numeric, as in // array('http://address.com') // array(array( // 'url' => 'http://address.com', // 'options' => array(...) // )) if (is_numeric($key)) { // if $values is an associative array containing one of "url", "options" and "data" entries, like // array( // 'url' => 'http://address.com', // 'options' => array(...) // ) if (is_array($values) && !empty(array_intersect(array('url', 'options', 'data'), array_keys($values)))) { // since "url" is mandatory, stop if not present if (!isset($values['url'])) trigger_error('<strong>url</strong> key is missing from argument', E_USER_ERROR); // keep everything as it is $result[] = $values; // if $values is not an array or not an associative array containing one of "url", "options" and "data" entries, like // 'http://address.com' } else { // it has to be the URL $result[] = array('url' => $values); } // if key is not numeric, as in // 'http://address.com' => array(...) } else { // the value has to be the "data" $result[] = array('url' => $key, 'data' => $values); } } // update the values $urls = $result; // if $urls is not an array, as in // 'http://address.com' } else { // it has to be the URL, and make it an array of arrays $urls = array(array('url' => $urls)); } // walk recursively through the array array_walk_recursive($urls, function(&$value) { // if we have to upload a file if (strpos($value, '@') === 0) // if PHP version is 5.5+ if (version_compare(PHP_VERSION, '5.5') >= 0) { // remove the @ from the name $file = substr($value, 1); // use CURLFile to prepare the file $value = new CURLFile($file); } }); // return the normalized array return $urls; }
php
private function _prepare_urls($urls) { // if $urls is *one* associative array containing one of "url", "options" and "data" entries if (is_array($urls) && !empty(array_intersect(array('url', 'options', 'data'), array_keys($urls)))) { // since "url" is mandatory, stop if not present if (!isset($urls['url'])) trigger_error('<strong>url</strong> key is missing from argument', E_USER_ERROR); // return as an array of arrays return array($urls); // if $urls is an array } elseif (is_array($urls)) { $result = array(); // iterate over the entries in the array foreach ($urls as $key => $values) { // if key is numeric, as in // array('http://address.com') // array(array( // 'url' => 'http://address.com', // 'options' => array(...) // )) if (is_numeric($key)) { // if $values is an associative array containing one of "url", "options" and "data" entries, like // array( // 'url' => 'http://address.com', // 'options' => array(...) // ) if (is_array($values) && !empty(array_intersect(array('url', 'options', 'data'), array_keys($values)))) { // since "url" is mandatory, stop if not present if (!isset($values['url'])) trigger_error('<strong>url</strong> key is missing from argument', E_USER_ERROR); // keep everything as it is $result[] = $values; // if $values is not an array or not an associative array containing one of "url", "options" and "data" entries, like // 'http://address.com' } else { // it has to be the URL $result[] = array('url' => $values); } // if key is not numeric, as in // 'http://address.com' => array(...) } else { // the value has to be the "data" $result[] = array('url' => $key, 'data' => $values); } } // update the values $urls = $result; // if $urls is not an array, as in // 'http://address.com' } else { // it has to be the URL, and make it an array of arrays $urls = array(array('url' => $urls)); } // walk recursively through the array array_walk_recursive($urls, function(&$value) { // if we have to upload a file if (strpos($value, '@') === 0) // if PHP version is 5.5+ if (version_compare(PHP_VERSION, '5.5') >= 0) { // remove the @ from the name $file = substr($value, 1); // use CURLFile to prepare the file $value = new CURLFile($file); } }); // return the normalized array return $urls; }
[ "private", "function", "_prepare_urls", "(", "$", "urls", ")", "{", "// if $urls is *one* associative array containing one of \"url\", \"options\" and \"data\" entries", "if", "(", "is_array", "(", "$", "urls", ")", "&&", "!", "empty", "(", "array_intersect", "(", "array", "(", "'url'", ",", "'options'", ",", "'data'", ")", ",", "array_keys", "(", "$", "urls", ")", ")", ")", ")", "{", "// since \"url\" is mandatory, stop if not present", "if", "(", "!", "isset", "(", "$", "urls", "[", "'url'", "]", ")", ")", "trigger_error", "(", "'<strong>url</strong> key is missing from argument'", ",", "E_USER_ERROR", ")", ";", "// return as an array of arrays", "return", "array", "(", "$", "urls", ")", ";", "// if $urls is an array", "}", "elseif", "(", "is_array", "(", "$", "urls", ")", ")", "{", "$", "result", "=", "array", "(", ")", ";", "// iterate over the entries in the array", "foreach", "(", "$", "urls", "as", "$", "key", "=>", "$", "values", ")", "{", "// if key is numeric, as in", "// array('http://address.com')", "// array(array(", "// 'url' => 'http://address.com',", "// 'options' => array(...)", "// ))", "if", "(", "is_numeric", "(", "$", "key", ")", ")", "{", "// if $values is an associative array containing one of \"url\", \"options\" and \"data\" entries, like", "// array(", "// 'url' => 'http://address.com',", "// 'options' => array(...)", "// )", "if", "(", "is_array", "(", "$", "values", ")", "&&", "!", "empty", "(", "array_intersect", "(", "array", "(", "'url'", ",", "'options'", ",", "'data'", ")", ",", "array_keys", "(", "$", "values", ")", ")", ")", ")", "{", "// since \"url\" is mandatory, stop if not present", "if", "(", "!", "isset", "(", "$", "values", "[", "'url'", "]", ")", ")", "trigger_error", "(", "'<strong>url</strong> key is missing from argument'", ",", "E_USER_ERROR", ")", ";", "// keep everything as it is", "$", "result", "[", "]", "=", "$", "values", ";", "// if $values is not an array or not an associative array containing one of \"url\", \"options\" and \"data\" entries, like", "// 'http://address.com'", "}", "else", "{", "// it has to be the URL", "$", "result", "[", "]", "=", "array", "(", "'url'", "=>", "$", "values", ")", ";", "}", "// if key is not numeric, as in", "// 'http://address.com' => array(...)", "}", "else", "{", "// the value has to be the \"data\"", "$", "result", "[", "]", "=", "array", "(", "'url'", "=>", "$", "key", ",", "'data'", "=>", "$", "values", ")", ";", "}", "}", "// update the values", "$", "urls", "=", "$", "result", ";", "// if $urls is not an array, as in", "// 'http://address.com'", "}", "else", "{", "// it has to be the URL, and make it an array of arrays", "$", "urls", "=", "array", "(", "array", "(", "'url'", "=>", "$", "urls", ")", ")", ";", "}", "// walk recursively through the array", "array_walk_recursive", "(", "$", "urls", ",", "function", "(", "&", "$", "value", ")", "{", "// if we have to upload a file", "if", "(", "strpos", "(", "$", "value", ",", "'@'", ")", "===", "0", ")", "// if PHP version is 5.5+", "if", "(", "version_compare", "(", "PHP_VERSION", ",", "'5.5'", ")", ">=", "0", ")", "{", "// remove the @ from the name", "$", "file", "=", "substr", "(", "$", "value", ",", "1", ")", ";", "// use CURLFile to prepare the file", "$", "value", "=", "new", "CURLFile", "(", "$", "file", ")", ";", "}", "}", ")", ";", "// return the normalized array", "return", "$", "urls", ";", "}" ]
Normalizes URLs. Since URLs can be given as a string, an array of URLs, one associative array or an array of associative arrays, this method normalizes all of those into an array of associative arrays. @return array @access private
[ "Normalizes", "URLs", "." ]
train
https://github.com/stefangabos/Zebra_cURL/blob/bf9f5b27ca5783cba97f51243bf1354ab18c1483/Zebra_cURL.php#L2743-L2837
stefangabos/Zebra_cURL
Zebra_cURL.php
Zebra_cURL._process
private function _process() { // if caching is enabled but path doesn't exist, or is not writable if ($this->cache !== false && (!is_dir($this->cache['path']) || !is_writable($this->cache['path']))) // trigger an error and stop execution trigger_error('Cache path does not exists or is not writable', E_USER_ERROR); // iterate through the requests to process foreach ($this->_requests as $index => $request) { // if callback function is defined but it doesn't exists if ($request['callback'] != '' && !is_callable($request['callback'])) // trigger an error and stop execution // the check is for when callback functions are defined as methods of a class trigger_error('Callback function "' . (is_array($request['callback']) ? array_pop($request['callback']) : $request['callback']) . '" does not exist', E_USER_ERROR); // if caching is enabled if ($this->cache !== false) { // get the name to be used for the cache file associated with the request $cache_file = $this->_get_cache_file_name($request); // if cache file exists and is not expired if (file_exists($cache_file) && filemtime($cache_file) + $this->cache['lifetime'] > time()) { // if we have a callback if ($request['callback'] != '') { // prepare the arguments to pass to the callback function $arguments = array_merge( // made of the result from the cache file... array(unserialize($this->cache['compress'] ? gzuncompress(file_get_contents($cache_file)) : file_get_contents($cache_file))), // ...and any additional arguments (minus the first 2) (array)$request['arguments'] ); // feed them as arguments to the callback function call_user_func_array($request['callback'], $arguments); // remove this request from the list so it doesn't get processed unset($this->_requests[$index]); } } } } // if there are any requests to process if (!empty($this->_requests)) { // initialize the multi handle // this will allow us to process multiple handles in parallel $this->_multi_handle = curl_multi_init(); // queue the first batch of requests // (as many as defined by the "threads" property, or less if there aren't as many requests) $this->_queue_requests(); // a flag telling the library if there are any requests currently processing $running = null; // loop do { // get status update while (($status = curl_multi_exec($this->_multi_handle, $running)) == CURLM_CALL_MULTI_PERFORM); // if no request has finished yet, keep looping if ($status != CURLM_OK) break; // if a request was just completed, we'll have to find out which one while ($info = curl_multi_info_read($this->_multi_handle)) { // get handle of the completed request $handle = $info['handle']; // get content associated with the handle $content = curl_multi_getcontent($handle); // get the handle's ID $resource_number = preg_replace('/Resource id #/', '', $handle); // get the information associated with the request $request = $this->_running['fh' . $resource_number]; // create a new object in which we will store all the data associated with the handle, // as properties of this object $result = new stdClass(); // get information about the request $result->info = curl_getinfo($handle); // extend the "info" property with the original URL $result->info = array('original_url' => $request['url']) + $result->info; // if request was a POST if (isset($request['options'][CURLOPT_POSTFIELDS]) && $request['options'][CURLOPT_POSTFIELDS]) // put POST parameters in the response $result->post = $request['options'][CURLOPT_POSTFIELDS]; // last request headers $result->headers['last_request'] = ( // if CURLINFO_HEADER_OUT is set isset($request['options'][CURLINFO_HEADER_OUT]) && // if CURLINFO_HEADER_OUT is TRUE $request['options'][CURLINFO_HEADER_OUT] == 1 && // if we actually have this information isset($result->info['request_header']) // extract request headers ) ? $this->_parse_headers($result->info['request_header'], true) : ''; // remove request headers information from its previous location unset($result->info['request_header']); // get headers (unless we were explicitly told not to) $result->headers['responses'] = (isset($request['options'][CURLOPT_HEADER]) && $request['options'][CURLOPT_HEADER] == 1) ? $this->_parse_headers(substr($content, 0, $result->info['header_size'])) : ''; // get output (unless we were explicitly told not to) $result->body = !isset($request['options'][CURLOPT_NOBODY]) || $request['options'][CURLOPT_NOBODY] == 0 ? (isset($request['options'][CURLOPT_HEADER]) && $request['options'][CURLOPT_HEADER] == 1 ? substr($content, $result->info['header_size']) : $content) : ''; // if _htmlentities is set to TRUE, we're not doing a binary transfer and we have a body, run htmlentities() on it if ($this->_htmlentities && !isset($request['options'][CURLOPT_BINARYTRANSFER]) && $result->body != '') { // since PHP 5.3.0, htmlentities will return an empty string if the input string contains an // invalid code unit sequence within the given encoding (utf-8 in our case) // so take care of that if (defined(ENT_IGNORE)) $result->body = htmlentities($result->body, ENT_IGNORE, 'utf-8'); // for PHP versions lower than 5.3.0 else htmlentities($result->body); } // get CURLs response code and associated message $result->response = array($this->_response_messages[$info['result']], $info['result']); // if we have a callback if (isset($request['callback']) && $request['callback'] != '') { // prepare the arguments to pass to the callback function $arguments = array_merge( // made of the "result" object... array($result), // ...and any additional arguments $request['arguments'] ); // if downloaded a file if (isset($request['options'][CURLOPT_BINARYTRANSFER]) && $request['options'][CURLOPT_BINARYTRANSFER]) { // we make a dummy array with the first first 2 elements (which we also remove from the $arguments[0]->info array) $tmp_array = array_splice($arguments[0]->info, 0, 2); // make available the name we saved the file with // (we need to merge the first 2 elements, our new array and the rest of the elements) $arguments[0]->info = array_merge($tmp_array, array('downloaded_filename' => $this->_running['fh' . $resource_number]['file_name']), $arguments[0]->info); } // feed them as arguments to the callback function // and save the callback's response, if any $callback_response = call_user_func_array($request['callback'], $arguments); // if no callback function, we assume the response is TRUE } else $callback_response = true; // if caching is enabled and the callback function did not return FALSE if ($this->cache !== false && $callback_response !== false) { // get the name of the cache file associated with the request $cache_file = $this->_get_cache_file_name($request); // cache the result file_put_contents($cache_file, $this->cache['compress'] ? gzcompress(serialize($result)) : serialize($result)); // set rights on the file chmod($cache_file, intval($this->cache['chmod'], 8)); } // if there are more URLs to process and we're don't pause between batches of requests, queue the next one(s) if (!empty($this->_requests) && !$this->pause_interval) $this->_queue_requests(); // remove the handle that we finished processing // this needs to be done *after* we've already queued a new URL for processing curl_multi_remove_handle($this->_multi_handle, $handle); // make sure the handle gets closed curl_close($handle); // if we downloaded a file if (isset($request['options'][CURLOPT_BINARYTRANSFER]) && $request['options'][CURLOPT_BINARYTRANSFER]) // close the associated file pointer fclose($this->_running['fh' . $resource_number]['file_handler']); // we don't need the information associated with this request anymore unset($this->_running['fh' . $resource_number]); } // waits until curl_multi_exec() returns CURLM_CALL_MULTI_PERFORM or until the timeout, whatever happens first // call usleep() if a select returns -1 - workaround for PHP bug: https://bugs.php.net/bug.php?id=61141 if ($running && curl_multi_select($this->_multi_handle) === -1) usleep(100); // as long as there are threads running or requests waiting in the queue } while ($running || !empty($this->_running)); // close the multi curl handle curl_multi_close($this->_multi_handle); } }
php
private function _process() { // if caching is enabled but path doesn't exist, or is not writable if ($this->cache !== false && (!is_dir($this->cache['path']) || !is_writable($this->cache['path']))) // trigger an error and stop execution trigger_error('Cache path does not exists or is not writable', E_USER_ERROR); // iterate through the requests to process foreach ($this->_requests as $index => $request) { // if callback function is defined but it doesn't exists if ($request['callback'] != '' && !is_callable($request['callback'])) // trigger an error and stop execution // the check is for when callback functions are defined as methods of a class trigger_error('Callback function "' . (is_array($request['callback']) ? array_pop($request['callback']) : $request['callback']) . '" does not exist', E_USER_ERROR); // if caching is enabled if ($this->cache !== false) { // get the name to be used for the cache file associated with the request $cache_file = $this->_get_cache_file_name($request); // if cache file exists and is not expired if (file_exists($cache_file) && filemtime($cache_file) + $this->cache['lifetime'] > time()) { // if we have a callback if ($request['callback'] != '') { // prepare the arguments to pass to the callback function $arguments = array_merge( // made of the result from the cache file... array(unserialize($this->cache['compress'] ? gzuncompress(file_get_contents($cache_file)) : file_get_contents($cache_file))), // ...and any additional arguments (minus the first 2) (array)$request['arguments'] ); // feed them as arguments to the callback function call_user_func_array($request['callback'], $arguments); // remove this request from the list so it doesn't get processed unset($this->_requests[$index]); } } } } // if there are any requests to process if (!empty($this->_requests)) { // initialize the multi handle // this will allow us to process multiple handles in parallel $this->_multi_handle = curl_multi_init(); // queue the first batch of requests // (as many as defined by the "threads" property, or less if there aren't as many requests) $this->_queue_requests(); // a flag telling the library if there are any requests currently processing $running = null; // loop do { // get status update while (($status = curl_multi_exec($this->_multi_handle, $running)) == CURLM_CALL_MULTI_PERFORM); // if no request has finished yet, keep looping if ($status != CURLM_OK) break; // if a request was just completed, we'll have to find out which one while ($info = curl_multi_info_read($this->_multi_handle)) { // get handle of the completed request $handle = $info['handle']; // get content associated with the handle $content = curl_multi_getcontent($handle); // get the handle's ID $resource_number = preg_replace('/Resource id #/', '', $handle); // get the information associated with the request $request = $this->_running['fh' . $resource_number]; // create a new object in which we will store all the data associated with the handle, // as properties of this object $result = new stdClass(); // get information about the request $result->info = curl_getinfo($handle); // extend the "info" property with the original URL $result->info = array('original_url' => $request['url']) + $result->info; // if request was a POST if (isset($request['options'][CURLOPT_POSTFIELDS]) && $request['options'][CURLOPT_POSTFIELDS]) // put POST parameters in the response $result->post = $request['options'][CURLOPT_POSTFIELDS]; // last request headers $result->headers['last_request'] = ( // if CURLINFO_HEADER_OUT is set isset($request['options'][CURLINFO_HEADER_OUT]) && // if CURLINFO_HEADER_OUT is TRUE $request['options'][CURLINFO_HEADER_OUT] == 1 && // if we actually have this information isset($result->info['request_header']) // extract request headers ) ? $this->_parse_headers($result->info['request_header'], true) : ''; // remove request headers information from its previous location unset($result->info['request_header']); // get headers (unless we were explicitly told not to) $result->headers['responses'] = (isset($request['options'][CURLOPT_HEADER]) && $request['options'][CURLOPT_HEADER] == 1) ? $this->_parse_headers(substr($content, 0, $result->info['header_size'])) : ''; // get output (unless we were explicitly told not to) $result->body = !isset($request['options'][CURLOPT_NOBODY]) || $request['options'][CURLOPT_NOBODY] == 0 ? (isset($request['options'][CURLOPT_HEADER]) && $request['options'][CURLOPT_HEADER] == 1 ? substr($content, $result->info['header_size']) : $content) : ''; // if _htmlentities is set to TRUE, we're not doing a binary transfer and we have a body, run htmlentities() on it if ($this->_htmlentities && !isset($request['options'][CURLOPT_BINARYTRANSFER]) && $result->body != '') { // since PHP 5.3.0, htmlentities will return an empty string if the input string contains an // invalid code unit sequence within the given encoding (utf-8 in our case) // so take care of that if (defined(ENT_IGNORE)) $result->body = htmlentities($result->body, ENT_IGNORE, 'utf-8'); // for PHP versions lower than 5.3.0 else htmlentities($result->body); } // get CURLs response code and associated message $result->response = array($this->_response_messages[$info['result']], $info['result']); // if we have a callback if (isset($request['callback']) && $request['callback'] != '') { // prepare the arguments to pass to the callback function $arguments = array_merge( // made of the "result" object... array($result), // ...and any additional arguments $request['arguments'] ); // if downloaded a file if (isset($request['options'][CURLOPT_BINARYTRANSFER]) && $request['options'][CURLOPT_BINARYTRANSFER]) { // we make a dummy array with the first first 2 elements (which we also remove from the $arguments[0]->info array) $tmp_array = array_splice($arguments[0]->info, 0, 2); // make available the name we saved the file with // (we need to merge the first 2 elements, our new array and the rest of the elements) $arguments[0]->info = array_merge($tmp_array, array('downloaded_filename' => $this->_running['fh' . $resource_number]['file_name']), $arguments[0]->info); } // feed them as arguments to the callback function // and save the callback's response, if any $callback_response = call_user_func_array($request['callback'], $arguments); // if no callback function, we assume the response is TRUE } else $callback_response = true; // if caching is enabled and the callback function did not return FALSE if ($this->cache !== false && $callback_response !== false) { // get the name of the cache file associated with the request $cache_file = $this->_get_cache_file_name($request); // cache the result file_put_contents($cache_file, $this->cache['compress'] ? gzcompress(serialize($result)) : serialize($result)); // set rights on the file chmod($cache_file, intval($this->cache['chmod'], 8)); } // if there are more URLs to process and we're don't pause between batches of requests, queue the next one(s) if (!empty($this->_requests) && !$this->pause_interval) $this->_queue_requests(); // remove the handle that we finished processing // this needs to be done *after* we've already queued a new URL for processing curl_multi_remove_handle($this->_multi_handle, $handle); // make sure the handle gets closed curl_close($handle); // if we downloaded a file if (isset($request['options'][CURLOPT_BINARYTRANSFER]) && $request['options'][CURLOPT_BINARYTRANSFER]) // close the associated file pointer fclose($this->_running['fh' . $resource_number]['file_handler']); // we don't need the information associated with this request anymore unset($this->_running['fh' . $resource_number]); } // waits until curl_multi_exec() returns CURLM_CALL_MULTI_PERFORM or until the timeout, whatever happens first // call usleep() if a select returns -1 - workaround for PHP bug: https://bugs.php.net/bug.php?id=61141 if ($running && curl_multi_select($this->_multi_handle) === -1) usleep(100); // as long as there are threads running or requests waiting in the queue } while ($running || !empty($this->_running)); // close the multi curl handle curl_multi_close($this->_multi_handle); } }
[ "private", "function", "_process", "(", ")", "{", "// if caching is enabled but path doesn't exist, or is not writable", "if", "(", "$", "this", "->", "cache", "!==", "false", "&&", "(", "!", "is_dir", "(", "$", "this", "->", "cache", "[", "'path'", "]", ")", "||", "!", "is_writable", "(", "$", "this", "->", "cache", "[", "'path'", "]", ")", ")", ")", "// trigger an error and stop execution", "trigger_error", "(", "'Cache path does not exists or is not writable'", ",", "E_USER_ERROR", ")", ";", "// iterate through the requests to process", "foreach", "(", "$", "this", "->", "_requests", "as", "$", "index", "=>", "$", "request", ")", "{", "// if callback function is defined but it doesn't exists", "if", "(", "$", "request", "[", "'callback'", "]", "!=", "''", "&&", "!", "is_callable", "(", "$", "request", "[", "'callback'", "]", ")", ")", "// trigger an error and stop execution", "// the check is for when callback functions are defined as methods of a class", "trigger_error", "(", "'Callback function \"'", ".", "(", "is_array", "(", "$", "request", "[", "'callback'", "]", ")", "?", "array_pop", "(", "$", "request", "[", "'callback'", "]", ")", ":", "$", "request", "[", "'callback'", "]", ")", ".", "'\" does not exist'", ",", "E_USER_ERROR", ")", ";", "// if caching is enabled", "if", "(", "$", "this", "->", "cache", "!==", "false", ")", "{", "// get the name to be used for the cache file associated with the request", "$", "cache_file", "=", "$", "this", "->", "_get_cache_file_name", "(", "$", "request", ")", ";", "// if cache file exists and is not expired", "if", "(", "file_exists", "(", "$", "cache_file", ")", "&&", "filemtime", "(", "$", "cache_file", ")", "+", "$", "this", "->", "cache", "[", "'lifetime'", "]", ">", "time", "(", ")", ")", "{", "// if we have a callback", "if", "(", "$", "request", "[", "'callback'", "]", "!=", "''", ")", "{", "// prepare the arguments to pass to the callback function", "$", "arguments", "=", "array_merge", "(", "// made of the result from the cache file...", "array", "(", "unserialize", "(", "$", "this", "->", "cache", "[", "'compress'", "]", "?", "gzuncompress", "(", "file_get_contents", "(", "$", "cache_file", ")", ")", ":", "file_get_contents", "(", "$", "cache_file", ")", ")", ")", ",", "// ...and any additional arguments (minus the first 2)", "(", "array", ")", "$", "request", "[", "'arguments'", "]", ")", ";", "// feed them as arguments to the callback function", "call_user_func_array", "(", "$", "request", "[", "'callback'", "]", ",", "$", "arguments", ")", ";", "// remove this request from the list so it doesn't get processed", "unset", "(", "$", "this", "->", "_requests", "[", "$", "index", "]", ")", ";", "}", "}", "}", "}", "// if there are any requests to process", "if", "(", "!", "empty", "(", "$", "this", "->", "_requests", ")", ")", "{", "// initialize the multi handle", "// this will allow us to process multiple handles in parallel", "$", "this", "->", "_multi_handle", "=", "curl_multi_init", "(", ")", ";", "// queue the first batch of requests", "// (as many as defined by the \"threads\" property, or less if there aren't as many requests)", "$", "this", "->", "_queue_requests", "(", ")", ";", "// a flag telling the library if there are any requests currently processing", "$", "running", "=", "null", ";", "// loop", "do", "{", "// get status update", "while", "(", "(", "$", "status", "=", "curl_multi_exec", "(", "$", "this", "->", "_multi_handle", ",", "$", "running", ")", ")", "==", "CURLM_CALL_MULTI_PERFORM", ")", ";", "// if no request has finished yet, keep looping", "if", "(", "$", "status", "!=", "CURLM_OK", ")", "break", ";", "// if a request was just completed, we'll have to find out which one", "while", "(", "$", "info", "=", "curl_multi_info_read", "(", "$", "this", "->", "_multi_handle", ")", ")", "{", "// get handle of the completed request", "$", "handle", "=", "$", "info", "[", "'handle'", "]", ";", "// get content associated with the handle", "$", "content", "=", "curl_multi_getcontent", "(", "$", "handle", ")", ";", "// get the handle's ID", "$", "resource_number", "=", "preg_replace", "(", "'/Resource id #/'", ",", "''", ",", "$", "handle", ")", ";", "// get the information associated with the request", "$", "request", "=", "$", "this", "->", "_running", "[", "'fh'", ".", "$", "resource_number", "]", ";", "// create a new object in which we will store all the data associated with the handle,", "// as properties of this object", "$", "result", "=", "new", "stdClass", "(", ")", ";", "// get information about the request", "$", "result", "->", "info", "=", "curl_getinfo", "(", "$", "handle", ")", ";", "// extend the \"info\" property with the original URL", "$", "result", "->", "info", "=", "array", "(", "'original_url'", "=>", "$", "request", "[", "'url'", "]", ")", "+", "$", "result", "->", "info", ";", "// if request was a POST", "if", "(", "isset", "(", "$", "request", "[", "'options'", "]", "[", "CURLOPT_POSTFIELDS", "]", ")", "&&", "$", "request", "[", "'options'", "]", "[", "CURLOPT_POSTFIELDS", "]", ")", "// put POST parameters in the response", "$", "result", "->", "post", "=", "$", "request", "[", "'options'", "]", "[", "CURLOPT_POSTFIELDS", "]", ";", "// last request headers", "$", "result", "->", "headers", "[", "'last_request'", "]", "=", "(", "// if CURLINFO_HEADER_OUT is set", "isset", "(", "$", "request", "[", "'options'", "]", "[", "CURLINFO_HEADER_OUT", "]", ")", "&&", "// if CURLINFO_HEADER_OUT is TRUE", "$", "request", "[", "'options'", "]", "[", "CURLINFO_HEADER_OUT", "]", "==", "1", "&&", "// if we actually have this information", "isset", "(", "$", "result", "->", "info", "[", "'request_header'", "]", ")", "// extract request headers", ")", "?", "$", "this", "->", "_parse_headers", "(", "$", "result", "->", "info", "[", "'request_header'", "]", ",", "true", ")", ":", "''", ";", "// remove request headers information from its previous location", "unset", "(", "$", "result", "->", "info", "[", "'request_header'", "]", ")", ";", "// get headers (unless we were explicitly told not to)", "$", "result", "->", "headers", "[", "'responses'", "]", "=", "(", "isset", "(", "$", "request", "[", "'options'", "]", "[", "CURLOPT_HEADER", "]", ")", "&&", "$", "request", "[", "'options'", "]", "[", "CURLOPT_HEADER", "]", "==", "1", ")", "?", "$", "this", "->", "_parse_headers", "(", "substr", "(", "$", "content", ",", "0", ",", "$", "result", "->", "info", "[", "'header_size'", "]", ")", ")", ":", "''", ";", "// get output (unless we were explicitly told not to)", "$", "result", "->", "body", "=", "!", "isset", "(", "$", "request", "[", "'options'", "]", "[", "CURLOPT_NOBODY", "]", ")", "||", "$", "request", "[", "'options'", "]", "[", "CURLOPT_NOBODY", "]", "==", "0", "?", "(", "isset", "(", "$", "request", "[", "'options'", "]", "[", "CURLOPT_HEADER", "]", ")", "&&", "$", "request", "[", "'options'", "]", "[", "CURLOPT_HEADER", "]", "==", "1", "?", "substr", "(", "$", "content", ",", "$", "result", "->", "info", "[", "'header_size'", "]", ")", ":", "$", "content", ")", ":", "''", ";", "// if _htmlentities is set to TRUE, we're not doing a binary transfer and we have a body, run htmlentities() on it", "if", "(", "$", "this", "->", "_htmlentities", "&&", "!", "isset", "(", "$", "request", "[", "'options'", "]", "[", "CURLOPT_BINARYTRANSFER", "]", ")", "&&", "$", "result", "->", "body", "!=", "''", ")", "{", "// since PHP 5.3.0, htmlentities will return an empty string if the input string contains an", "// invalid code unit sequence within the given encoding (utf-8 in our case)", "// so take care of that", "if", "(", "defined", "(", "ENT_IGNORE", ")", ")", "$", "result", "->", "body", "=", "htmlentities", "(", "$", "result", "->", "body", ",", "ENT_IGNORE", ",", "'utf-8'", ")", ";", "// for PHP versions lower than 5.3.0", "else", "htmlentities", "(", "$", "result", "->", "body", ")", ";", "}", "// get CURLs response code and associated message", "$", "result", "->", "response", "=", "array", "(", "$", "this", "->", "_response_messages", "[", "$", "info", "[", "'result'", "]", "]", ",", "$", "info", "[", "'result'", "]", ")", ";", "// if we have a callback", "if", "(", "isset", "(", "$", "request", "[", "'callback'", "]", ")", "&&", "$", "request", "[", "'callback'", "]", "!=", "''", ")", "{", "// prepare the arguments to pass to the callback function", "$", "arguments", "=", "array_merge", "(", "// made of the \"result\" object...", "array", "(", "$", "result", ")", ",", "// ...and any additional arguments", "$", "request", "[", "'arguments'", "]", ")", ";", "// if downloaded a file", "if", "(", "isset", "(", "$", "request", "[", "'options'", "]", "[", "CURLOPT_BINARYTRANSFER", "]", ")", "&&", "$", "request", "[", "'options'", "]", "[", "CURLOPT_BINARYTRANSFER", "]", ")", "{", "// we make a dummy array with the first first 2 elements (which we also remove from the $arguments[0]->info array)", "$", "tmp_array", "=", "array_splice", "(", "$", "arguments", "[", "0", "]", "->", "info", ",", "0", ",", "2", ")", ";", "// make available the name we saved the file with", "// (we need to merge the first 2 elements, our new array and the rest of the elements)", "$", "arguments", "[", "0", "]", "->", "info", "=", "array_merge", "(", "$", "tmp_array", ",", "array", "(", "'downloaded_filename'", "=>", "$", "this", "->", "_running", "[", "'fh'", ".", "$", "resource_number", "]", "[", "'file_name'", "]", ")", ",", "$", "arguments", "[", "0", "]", "->", "info", ")", ";", "}", "// feed them as arguments to the callback function", "// and save the callback's response, if any", "$", "callback_response", "=", "call_user_func_array", "(", "$", "request", "[", "'callback'", "]", ",", "$", "arguments", ")", ";", "// if no callback function, we assume the response is TRUE", "}", "else", "$", "callback_response", "=", "true", ";", "// if caching is enabled and the callback function did not return FALSE", "if", "(", "$", "this", "->", "cache", "!==", "false", "&&", "$", "callback_response", "!==", "false", ")", "{", "// get the name of the cache file associated with the request", "$", "cache_file", "=", "$", "this", "->", "_get_cache_file_name", "(", "$", "request", ")", ";", "// cache the result", "file_put_contents", "(", "$", "cache_file", ",", "$", "this", "->", "cache", "[", "'compress'", "]", "?", "gzcompress", "(", "serialize", "(", "$", "result", ")", ")", ":", "serialize", "(", "$", "result", ")", ")", ";", "// set rights on the file", "chmod", "(", "$", "cache_file", ",", "intval", "(", "$", "this", "->", "cache", "[", "'chmod'", "]", ",", "8", ")", ")", ";", "}", "// if there are more URLs to process and we're don't pause between batches of requests, queue the next one(s)", "if", "(", "!", "empty", "(", "$", "this", "->", "_requests", ")", "&&", "!", "$", "this", "->", "pause_interval", ")", "$", "this", "->", "_queue_requests", "(", ")", ";", "// remove the handle that we finished processing", "// this needs to be done *after* we've already queued a new URL for processing", "curl_multi_remove_handle", "(", "$", "this", "->", "_multi_handle", ",", "$", "handle", ")", ";", "// make sure the handle gets closed", "curl_close", "(", "$", "handle", ")", ";", "// if we downloaded a file", "if", "(", "isset", "(", "$", "request", "[", "'options'", "]", "[", "CURLOPT_BINARYTRANSFER", "]", ")", "&&", "$", "request", "[", "'options'", "]", "[", "CURLOPT_BINARYTRANSFER", "]", ")", "// close the associated file pointer", "fclose", "(", "$", "this", "->", "_running", "[", "'fh'", ".", "$", "resource_number", "]", "[", "'file_handler'", "]", ")", ";", "// we don't need the information associated with this request anymore", "unset", "(", "$", "this", "->", "_running", "[", "'fh'", ".", "$", "resource_number", "]", ")", ";", "}", "// waits until curl_multi_exec() returns CURLM_CALL_MULTI_PERFORM or until the timeout, whatever happens first", "// call usleep() if a select returns -1 - workaround for PHP bug: https://bugs.php.net/bug.php?id=61141", "if", "(", "$", "running", "&&", "curl_multi_select", "(", "$", "this", "->", "_multi_handle", ")", "===", "-", "1", ")", "usleep", "(", "100", ")", ";", "// as long as there are threads running or requests waiting in the queue", "}", "while", "(", "$", "running", "||", "!", "empty", "(", "$", "this", "->", "_running", ")", ")", ";", "// close the multi curl handle", "curl_multi_close", "(", "$", "this", "->", "_multi_handle", ")", ";", "}", "}" ]
Does the actual work. @return void @access private
[ "Does", "the", "actual", "work", "." ]
train
https://github.com/stefangabos/Zebra_cURL/blob/bf9f5b27ca5783cba97f51243bf1354ab18c1483/Zebra_cURL.php#L2846-L3089
stefangabos/Zebra_cURL
Zebra_cURL.php
Zebra_cURL._process_paused
private function _process_paused() { // copy all requests to another variable $urls = $this->_requests; // while there are URLs to process while (!empty($urls)) { // get from the entire list of requests as many as specified by the "threads" property $this->_requests = array_splice($urls, 0, $this->threads, array()); // process those requests $this->_process(); // wait for as many seconds as specified by the "pause_interval" property if (!empty($urls)) sleep($this->pause_interval); } }
php
private function _process_paused() { // copy all requests to another variable $urls = $this->_requests; // while there are URLs to process while (!empty($urls)) { // get from the entire list of requests as many as specified by the "threads" property $this->_requests = array_splice($urls, 0, $this->threads, array()); // process those requests $this->_process(); // wait for as many seconds as specified by the "pause_interval" property if (!empty($urls)) sleep($this->pause_interval); } }
[ "private", "function", "_process_paused", "(", ")", "{", "// copy all requests to another variable", "$", "urls", "=", "$", "this", "->", "_requests", ";", "// while there are URLs to process", "while", "(", "!", "empty", "(", "$", "urls", ")", ")", "{", "// get from the entire list of requests as many as specified by the \"threads\" property", "$", "this", "->", "_requests", "=", "array_splice", "(", "$", "urls", ",", "0", ",", "$", "this", "->", "threads", ",", "array", "(", ")", ")", ";", "// process those requests", "$", "this", "->", "_process", "(", ")", ";", "// wait for as many seconds as specified by the \"pause_interval\" property", "if", "(", "!", "empty", "(", "$", "urls", ")", ")", "sleep", "(", "$", "this", "->", "pause_interval", ")", ";", "}", "}" ]
A wrapper for the {@link _process} method used when we need to pause between batches of requests to process. @return void @access private
[ "A", "wrapper", "for", "the", "{", "@link", "_process", "}", "method", "used", "when", "we", "need", "to", "pause", "between", "batches", "of", "requests", "to", "process", "." ]
train
https://github.com/stefangabos/Zebra_cURL/blob/bf9f5b27ca5783cba97f51243bf1354ab18c1483/Zebra_cURL.php#L3099-L3118
stefangabos/Zebra_cURL
Zebra_cURL.php
Zebra_cURL._queue_requests
private function _queue_requests() { // get the number of remaining urls $requests_count = count($this->_requests); // iterate through the items in the queue for ($i = 0; $i < ($requests_count < $this->threads ? $requests_count : $this->threads); $i++) { // remove the first request from the queue $request = array_shift($this->_requests); // initialize individual cURL handle with the URL $handle = curl_init($request['url']); // get the handle's ID $resource_number = preg_replace('/Resource id #/', '', $handle); // if we're downloading something if (isset($request['options'][CURLOPT_BINARYTRANSFER]) && $request['options'][CURLOPT_BINARYTRANSFER]) { // use parse_url to analyze the string // we use this so we won't have hashtags and/or query string in the file's name later on $parsed = parse_url($request['url']); // the name to save the file by // if the downloaded path refers to something with a query string (i.e. download.php?foo=bar&w=1000&h=1000) // the downloaded file's name would be "download.php" and, if you are downloading multiple files, each one // would overwrite the previous one; therefore we use an md5 of the query string in this case $request['file_name'] = $request['path'] . (isset($parsed['query']) && $parsed['query'] != '' ? md5($parsed['query']) : basename($parsed['path'])); // open a file and save the file pointer $request['file_handler'] = fopen($request['file_name'], 'w+'); // tell libcurl to use the file for streaming the download $this->option(CURLOPT_FILE, $request['file_handler']); } // set request's options foreach ($request['options'] as $key => $value) $this->option($key, $value); // in some cases, CURLOPT_HTTPAUTH and CURLOPT_USERPWD need to be set as last options in order to work $options_to_be_set_last = array(10005, 107); // iterate through all the options foreach ($this->options as $key => $value) // if this option is one of those to be set at the end if (in_array($key, $options_to_be_set_last)) { // remove the option from where it is unset($this->options[$key]); // add option at the end $this->options[$key] = $value; } // set options for the handle curl_setopt_array($handle, $this->options); // add the normal handle to the multi handle curl_multi_add_handle($this->_multi_handle, $handle); // add request to the list of running requests $this->_running['fh' . $resource_number] = $request; } }
php
private function _queue_requests() { // get the number of remaining urls $requests_count = count($this->_requests); // iterate through the items in the queue for ($i = 0; $i < ($requests_count < $this->threads ? $requests_count : $this->threads); $i++) { // remove the first request from the queue $request = array_shift($this->_requests); // initialize individual cURL handle with the URL $handle = curl_init($request['url']); // get the handle's ID $resource_number = preg_replace('/Resource id #/', '', $handle); // if we're downloading something if (isset($request['options'][CURLOPT_BINARYTRANSFER]) && $request['options'][CURLOPT_BINARYTRANSFER]) { // use parse_url to analyze the string // we use this so we won't have hashtags and/or query string in the file's name later on $parsed = parse_url($request['url']); // the name to save the file by // if the downloaded path refers to something with a query string (i.e. download.php?foo=bar&w=1000&h=1000) // the downloaded file's name would be "download.php" and, if you are downloading multiple files, each one // would overwrite the previous one; therefore we use an md5 of the query string in this case $request['file_name'] = $request['path'] . (isset($parsed['query']) && $parsed['query'] != '' ? md5($parsed['query']) : basename($parsed['path'])); // open a file and save the file pointer $request['file_handler'] = fopen($request['file_name'], 'w+'); // tell libcurl to use the file for streaming the download $this->option(CURLOPT_FILE, $request['file_handler']); } // set request's options foreach ($request['options'] as $key => $value) $this->option($key, $value); // in some cases, CURLOPT_HTTPAUTH and CURLOPT_USERPWD need to be set as last options in order to work $options_to_be_set_last = array(10005, 107); // iterate through all the options foreach ($this->options as $key => $value) // if this option is one of those to be set at the end if (in_array($key, $options_to_be_set_last)) { // remove the option from where it is unset($this->options[$key]); // add option at the end $this->options[$key] = $value; } // set options for the handle curl_setopt_array($handle, $this->options); // add the normal handle to the multi handle curl_multi_add_handle($this->_multi_handle, $handle); // add request to the list of running requests $this->_running['fh' . $resource_number] = $request; } }
[ "private", "function", "_queue_requests", "(", ")", "{", "// get the number of remaining urls", "$", "requests_count", "=", "count", "(", "$", "this", "->", "_requests", ")", ";", "// iterate through the items in the queue", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "(", "$", "requests_count", "<", "$", "this", "->", "threads", "?", "$", "requests_count", ":", "$", "this", "->", "threads", ")", ";", "$", "i", "++", ")", "{", "// remove the first request from the queue", "$", "request", "=", "array_shift", "(", "$", "this", "->", "_requests", ")", ";", "// initialize individual cURL handle with the URL", "$", "handle", "=", "curl_init", "(", "$", "request", "[", "'url'", "]", ")", ";", "// get the handle's ID", "$", "resource_number", "=", "preg_replace", "(", "'/Resource id #/'", ",", "''", ",", "$", "handle", ")", ";", "// if we're downloading something", "if", "(", "isset", "(", "$", "request", "[", "'options'", "]", "[", "CURLOPT_BINARYTRANSFER", "]", ")", "&&", "$", "request", "[", "'options'", "]", "[", "CURLOPT_BINARYTRANSFER", "]", ")", "{", "// use parse_url to analyze the string", "// we use this so we won't have hashtags and/or query string in the file's name later on", "$", "parsed", "=", "parse_url", "(", "$", "request", "[", "'url'", "]", ")", ";", "// the name to save the file by", "// if the downloaded path refers to something with a query string (i.e. download.php?foo=bar&w=1000&h=1000)", "// the downloaded file's name would be \"download.php\" and, if you are downloading multiple files, each one", "// would overwrite the previous one; therefore we use an md5 of the query string in this case", "$", "request", "[", "'file_name'", "]", "=", "$", "request", "[", "'path'", "]", ".", "(", "isset", "(", "$", "parsed", "[", "'query'", "]", ")", "&&", "$", "parsed", "[", "'query'", "]", "!=", "''", "?", "md5", "(", "$", "parsed", "[", "'query'", "]", ")", ":", "basename", "(", "$", "parsed", "[", "'path'", "]", ")", ")", ";", "// open a file and save the file pointer", "$", "request", "[", "'file_handler'", "]", "=", "fopen", "(", "$", "request", "[", "'file_name'", "]", ",", "'w+'", ")", ";", "// tell libcurl to use the file for streaming the download", "$", "this", "->", "option", "(", "CURLOPT_FILE", ",", "$", "request", "[", "'file_handler'", "]", ")", ";", "}", "// set request's options", "foreach", "(", "$", "request", "[", "'options'", "]", "as", "$", "key", "=>", "$", "value", ")", "$", "this", "->", "option", "(", "$", "key", ",", "$", "value", ")", ";", "// in some cases, CURLOPT_HTTPAUTH and CURLOPT_USERPWD need to be set as last options in order to work", "$", "options_to_be_set_last", "=", "array", "(", "10005", ",", "107", ")", ";", "// iterate through all the options", "foreach", "(", "$", "this", "->", "options", "as", "$", "key", "=>", "$", "value", ")", "// if this option is one of those to be set at the end", "if", "(", "in_array", "(", "$", "key", ",", "$", "options_to_be_set_last", ")", ")", "{", "// remove the option from where it is", "unset", "(", "$", "this", "->", "options", "[", "$", "key", "]", ")", ";", "// add option at the end", "$", "this", "->", "options", "[", "$", "key", "]", "=", "$", "value", ";", "}", "// set options for the handle", "curl_setopt_array", "(", "$", "handle", ",", "$", "this", "->", "options", ")", ";", "// add the normal handle to the multi handle", "curl_multi_add_handle", "(", "$", "this", "->", "_multi_handle", ",", "$", "handle", ")", ";", "// add request to the list of running requests", "$", "this", "->", "_running", "[", "'fh'", ".", "$", "resource_number", "]", "=", "$", "request", ";", "}", "}" ]
A helper method used by the {@link _process} method, taking care of keeping a constant number of requests queued, so that as soon as one request finishes another one will instantly take its place, thus making sure that the maximum allowed number of parallel threads are running all the time. @return void @access private
[ "A", "helper", "method", "used", "by", "the", "{", "@link", "_process", "}", "method", "taking", "care", "of", "keeping", "a", "constant", "number", "of", "requests", "queued", "so", "that", "as", "soon", "as", "one", "request", "finishes", "another", "one", "will", "instantly", "take", "its", "place", "thus", "making", "sure", "that", "the", "maximum", "allowed", "number", "of", "parallel", "threads", "are", "running", "all", "the", "time", "." ]
train
https://github.com/stefangabos/Zebra_cURL/blob/bf9f5b27ca5783cba97f51243bf1354ab18c1483/Zebra_cURL.php#L3129-L3198
stefangabos/Zebra_cURL
Zebra_cURL.php
Zebra_cURL._user_agent
private function _user_agent() { // browser version: 9 or 10 $version = rand(9, 10); // windows version; here are the meanings: // Windows NT 6.2 -> Windows 8 // can have IE10 // Windows NT 6.1 -> Windows 7 // can have IE9 or IE10 // Windows NT 6.0 -> Windows Vista // can have IE9 $major_version = 6; $minor_version = // for IE9 Windows can have "0", "1" or "2" as minor version number $version == 8 || $version == 9 ? rand(0, 2) : // for IE10 Windows will have "2" as major version number 2; // add some extra information $extras = rand(0, 3); // return the random user agent string return 'Mozilla/5.0 (compatible; MSIE ' . $version . '.0; Windows NT ' . $major_version . '.' . $minor_version . ($extras == 1 ? '; WOW64' : ($extras == 2 ? '; Win64; IA64' : ($extras == 3 ? '; Win64; x64' : ''))) . ')'; }
php
private function _user_agent() { // browser version: 9 or 10 $version = rand(9, 10); // windows version; here are the meanings: // Windows NT 6.2 -> Windows 8 // can have IE10 // Windows NT 6.1 -> Windows 7 // can have IE9 or IE10 // Windows NT 6.0 -> Windows Vista // can have IE9 $major_version = 6; $minor_version = // for IE9 Windows can have "0", "1" or "2" as minor version number $version == 8 || $version == 9 ? rand(0, 2) : // for IE10 Windows will have "2" as major version number 2; // add some extra information $extras = rand(0, 3); // return the random user agent string return 'Mozilla/5.0 (compatible; MSIE ' . $version . '.0; Windows NT ' . $major_version . '.' . $minor_version . ($extras == 1 ? '; WOW64' : ($extras == 2 ? '; Win64; IA64' : ($extras == 3 ? '; Win64; x64' : ''))) . ')'; }
[ "private", "function", "_user_agent", "(", ")", "{", "// browser version: 9 or 10", "$", "version", "=", "rand", "(", "9", ",", "10", ")", ";", "// windows version; here are the meanings:", "// Windows NT 6.2 -> Windows 8 // can have IE10", "// Windows NT 6.1 -> Windows 7 // can have IE9 or IE10", "// Windows NT 6.0 -> Windows Vista // can have IE9", "$", "major_version", "=", "6", ";", "$", "minor_version", "=", "// for IE9 Windows can have \"0\", \"1\" or \"2\" as minor version number", "$", "version", "==", "8", "||", "$", "version", "==", "9", "?", "rand", "(", "0", ",", "2", ")", ":", "// for IE10 Windows will have \"2\" as major version number", "2", ";", "// add some extra information", "$", "extras", "=", "rand", "(", "0", ",", "3", ")", ";", "// return the random user agent string", "return", "'Mozilla/5.0 (compatible; MSIE '", ".", "$", "version", ".", "'.0; Windows NT '", ".", "$", "major_version", ".", "'.'", ".", "$", "minor_version", ".", "(", "$", "extras", "==", "1", "?", "'; WOW64'", ":", "(", "$", "extras", "==", "2", "?", "'; Win64; IA64'", ":", "(", "$", "extras", "==", "3", "?", "'; Win64; x64'", ":", "''", ")", ")", ")", ".", "')'", ";", "}" ]
Generates a (slightly) random user agent (Internet Explorer 9 or 10, on Windows Vista, 7 or 8, with other extra strings) Some web services will not respond unless a valid user-agent string is provided. @return void @access private
[ "Generates", "a", "(", "slightly", ")", "random", "user", "agent", "(", "Internet", "Explorer", "9", "or", "10", "on", "Windows", "Vista", "7", "or", "8", "with", "other", "extra", "strings", ")" ]
train
https://github.com/stefangabos/Zebra_cURL/blob/bf9f5b27ca5783cba97f51243bf1354ab18c1483/Zebra_cURL.php#L3210-L3235
MattKetmo/EmailChecker
src/EmailChecker/Constraints/NotThrowawayEmailValidator.php
NotThrowawayEmailValidator.validate
public function validate($value, Constraint $constraint) { if (null === $value || '' === $value) { return; } if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) { throw new UnexpectedTypeException($value, 'string'); } if (!$this->emailChecker->isValid($value)) { $this->context->addViolation($constraint->message); } }
php
public function validate($value, Constraint $constraint) { if (null === $value || '' === $value) { return; } if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) { throw new UnexpectedTypeException($value, 'string'); } if (!$this->emailChecker->isValid($value)) { $this->context->addViolation($constraint->message); } }
[ "public", "function", "validate", "(", "$", "value", ",", "Constraint", "$", "constraint", ")", "{", "if", "(", "null", "===", "$", "value", "||", "''", "===", "$", "value", ")", "{", "return", ";", "}", "if", "(", "!", "is_scalar", "(", "$", "value", ")", "&&", "!", "(", "is_object", "(", "$", "value", ")", "&&", "method_exists", "(", "$", "value", ",", "'__toString'", ")", ")", ")", "{", "throw", "new", "UnexpectedTypeException", "(", "$", "value", ",", "'string'", ")", ";", "}", "if", "(", "!", "$", "this", "->", "emailChecker", "->", "isValid", "(", "$", "value", ")", ")", "{", "$", "this", "->", "context", "->", "addViolation", "(", "$", "constraint", "->", "message", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/MattKetmo/EmailChecker/blob/678a50f4ccb9e13f16116fffa8d93ab70b83553d/src/EmailChecker/Constraints/NotThrowawayEmailValidator.php#L38-L51
MattKetmo/EmailChecker
src/EmailChecker/Laravel/EmailCheckerServiceProvider.php
EmailCheckerServiceProvider.register
public function register() { /* * Register the e-mail checker */ $this->app->singleton(EmailChecker::class, function ($app) { return new EmailChecker(); }); /* * Alias the dependency for ease. */ $this->app->alias(EmailChecker::class, 'email.checker'); }
php
public function register() { /* * Register the e-mail checker */ $this->app->singleton(EmailChecker::class, function ($app) { return new EmailChecker(); }); /* * Alias the dependency for ease. */ $this->app->alias(EmailChecker::class, 'email.checker'); }
[ "public", "function", "register", "(", ")", "{", "/*\n * Register the e-mail checker\n */", "$", "this", "->", "app", "->", "singleton", "(", "EmailChecker", "::", "class", ",", "function", "(", "$", "app", ")", "{", "return", "new", "EmailChecker", "(", ")", ";", "}", ")", ";", "/*\n * Alias the dependency for ease.\n */", "$", "this", "->", "app", "->", "alias", "(", "EmailChecker", "::", "class", ",", "'email.checker'", ")", ";", "}" ]
Register the factory in the application container.
[ "Register", "the", "factory", "in", "the", "application", "container", "." ]
train
https://github.com/MattKetmo/EmailChecker/blob/678a50f4ccb9e13f16116fffa8d93ab70b83553d/src/EmailChecker/Laravel/EmailCheckerServiceProvider.php#L28-L41
MattKetmo/EmailChecker
src/EmailChecker/Laravel/EmailCheckerServiceProvider.php
EmailCheckerServiceProvider.boot
public function boot(EmailChecker $checker) { /* * Add a custom validator filter. */ $check = function ($attr, $value, $param, $validator) use ($checker) { return $checker->isValid($value); }; Validator::extend( 'not_throw_away', $check, 'The :attribute domain is invalid.' ); }
php
public function boot(EmailChecker $checker) { /* * Add a custom validator filter. */ $check = function ($attr, $value, $param, $validator) use ($checker) { return $checker->isValid($value); }; Validator::extend( 'not_throw_away', $check, 'The :attribute domain is invalid.' ); }
[ "public", "function", "boot", "(", "EmailChecker", "$", "checker", ")", "{", "/*\n * Add a custom validator filter.\n */", "$", "check", "=", "function", "(", "$", "attr", ",", "$", "value", ",", "$", "param", ",", "$", "validator", ")", "use", "(", "$", "checker", ")", "{", "return", "$", "checker", "->", "isValid", "(", "$", "value", ")", ";", "}", ";", "Validator", "::", "extend", "(", "'not_throw_away'", ",", "$", "check", ",", "'The :attribute domain is invalid.'", ")", ";", "}" ]
Bootstrap any application services.
[ "Bootstrap", "any", "application", "services", "." ]
train
https://github.com/MattKetmo/EmailChecker/blob/678a50f4ccb9e13f16116fffa8d93ab70b83553d/src/EmailChecker/Laravel/EmailCheckerServiceProvider.php#L46-L58
MattKetmo/EmailChecker
src/EmailChecker/Adapter/AgregatorAdapter.php
AgregatorAdapter.isThrowawayDomain
public function isThrowawayDomain($domain) { foreach ($this->adapters as $adapter) { if ($adapter->isThrowawayDomain($domain)) { return true; } } return false; }
php
public function isThrowawayDomain($domain) { foreach ($this->adapters as $adapter) { if ($adapter->isThrowawayDomain($domain)) { return true; } } return false; }
[ "public", "function", "isThrowawayDomain", "(", "$", "domain", ")", "{", "foreach", "(", "$", "this", "->", "adapters", "as", "$", "adapter", ")", "{", "if", "(", "$", "adapter", "->", "isThrowawayDomain", "(", "$", "domain", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/MattKetmo/EmailChecker/blob/678a50f4ccb9e13f16116fffa8d93ab70b83553d/src/EmailChecker/Adapter/AgregatorAdapter.php#L44-L53
MattKetmo/EmailChecker
src/EmailChecker/Utilities.php
Utilities.parseEmailAddress
public static function parseEmailAddress($email) { $pattern = sprintf('/^(?<local>%s)@(?<domain>%s)$/iD', self::EMAIL_REGEX_LOCAL, self::EMAIL_REGEX_DOMAIN); if (!preg_match($pattern, $email, $parts)) { throw new InvalidEmailException(sprintf('"%s" is not a valid email', $email)); } return array_map('strtolower', [$parts['local'], $parts['domain']]); }
php
public static function parseEmailAddress($email) { $pattern = sprintf('/^(?<local>%s)@(?<domain>%s)$/iD', self::EMAIL_REGEX_LOCAL, self::EMAIL_REGEX_DOMAIN); if (!preg_match($pattern, $email, $parts)) { throw new InvalidEmailException(sprintf('"%s" is not a valid email', $email)); } return array_map('strtolower', [$parts['local'], $parts['domain']]); }
[ "public", "static", "function", "parseEmailAddress", "(", "$", "email", ")", "{", "$", "pattern", "=", "sprintf", "(", "'/^(?<local>%s)@(?<domain>%s)$/iD'", ",", "self", "::", "EMAIL_REGEX_LOCAL", ",", "self", "::", "EMAIL_REGEX_DOMAIN", ")", ";", "if", "(", "!", "preg_match", "(", "$", "pattern", ",", "$", "email", ",", "$", "parts", ")", ")", "{", "throw", "new", "InvalidEmailException", "(", "sprintf", "(", "'\"%s\" is not a valid email'", ",", "$", "email", ")", ")", ";", "}", "return", "array_map", "(", "'strtolower'", ",", "[", "$", "parts", "[", "'local'", "]", ",", "$", "parts", "[", "'domain'", "]", "]", ")", ";", "}" ]
Extract parts of an email address. @param string $email The email address to parse @return array The parts of the email. First the local part, then the domain
[ "Extract", "parts", "of", "an", "email", "address", "." ]
train
https://github.com/MattKetmo/EmailChecker/blob/678a50f4ccb9e13f16116fffa8d93ab70b83553d/src/EmailChecker/Utilities.php#L33-L42
MattKetmo/EmailChecker
src/EmailChecker/Utilities.php
Utilities.parseLines
public static function parseLines($content) { // Split by line $lines = explode("\n", $content); // Trim and convert to lowercase $lines = array_map('trim', $lines); $lines = array_map('strtolower', $lines); // Remove empty lines and comments $lines = array_filter($lines, function ($line) { return (0 === strlen($line) || '#' === $line[0]) ? false : $line; }); return $lines; }
php
public static function parseLines($content) { // Split by line $lines = explode("\n", $content); // Trim and convert to lowercase $lines = array_map('trim', $lines); $lines = array_map('strtolower', $lines); // Remove empty lines and comments $lines = array_filter($lines, function ($line) { return (0 === strlen($line) || '#' === $line[0]) ? false : $line; }); return $lines; }
[ "public", "static", "function", "parseLines", "(", "$", "content", ")", "{", "// Split by line", "$", "lines", "=", "explode", "(", "\"\\n\"", ",", "$", "content", ")", ";", "// Trim and convert to lowercase", "$", "lines", "=", "array_map", "(", "'trim'", ",", "$", "lines", ")", ";", "$", "lines", "=", "array_map", "(", "'strtolower'", ",", "$", "lines", ")", ";", "// Remove empty lines and comments", "$", "lines", "=", "array_filter", "(", "$", "lines", ",", "function", "(", "$", "line", ")", "{", "return", "(", "0", "===", "strlen", "(", "$", "line", ")", "||", "'#'", "===", "$", "line", "[", "0", "]", ")", "?", "false", ":", "$", "line", ";", "}", ")", ";", "return", "$", "lines", ";", "}" ]
Parse content and extract lines. @param string $content The content to parse @return array Array of cleaned string
[ "Parse", "content", "and", "extract", "lines", "." ]
train
https://github.com/MattKetmo/EmailChecker/blob/678a50f4ccb9e13f16116fffa8d93ab70b83553d/src/EmailChecker/Utilities.php#L51-L66
MattKetmo/EmailChecker
src/EmailChecker/EmailChecker.php
EmailChecker.isValid
public function isValid($email) { if (false === $email = filter_var($email, FILTER_VALIDATE_EMAIL)) { return false; } try { list($local, $domain) = Utilities::parseEmailAddress($email); } catch (InvalidEmailException $e) { return false; } return !$this->adapter->isThrowawayDomain($domain); }
php
public function isValid($email) { if (false === $email = filter_var($email, FILTER_VALIDATE_EMAIL)) { return false; } try { list($local, $domain) = Utilities::parseEmailAddress($email); } catch (InvalidEmailException $e) { return false; } return !$this->adapter->isThrowawayDomain($domain); }
[ "public", "function", "isValid", "(", "$", "email", ")", "{", "if", "(", "false", "===", "$", "email", "=", "filter_var", "(", "$", "email", ",", "FILTER_VALIDATE_EMAIL", ")", ")", "{", "return", "false", ";", "}", "try", "{", "list", "(", "$", "local", ",", "$", "domain", ")", "=", "Utilities", "::", "parseEmailAddress", "(", "$", "email", ")", ";", "}", "catch", "(", "InvalidEmailException", "$", "e", ")", "{", "return", "false", ";", "}", "return", "!", "$", "this", "->", "adapter", "->", "isThrowawayDomain", "(", "$", "domain", ")", ";", "}" ]
Check if it's a valid email, ie. not a throwaway email. @param string $email The email to check @return bool true for a throwaway email
[ "Check", "if", "it", "s", "a", "valid", "email", "ie", ".", "not", "a", "throwaway", "email", "." ]
train
https://github.com/MattKetmo/EmailChecker/blob/678a50f4ccb9e13f16116fffa8d93ab70b83553d/src/EmailChecker/EmailChecker.php#L42-L55
drutiny/drutiny
src/Assessment.php
Assessment.assessTarget
public function assessTarget(TargetInterface $target, array $policies, \DateTime $start = NULL, \DateTime $end = NULL, $remediate = FALSE) { $start = $start ?: new \DateTime('-1 day'); $end = $end ?: new \DateTime(); $policies = array_filter($policies, function ($policy) { return $policy instanceof Policy; }); $log = Container::getLogger(); $is_progress_bar = $log instanceof ProgressBar; foreach ($policies as $policy) { if ($is_progress_bar) { $log->setTopic($this->uri . '][' . $policy->get('title')); } $log->info("Assessing policy..."); // Setup the sandbox to run the assessment. $sandbox = new Sandbox($target, $policy, $this); $sandbox->setReportingPeriod($start, $end); $response = $sandbox->run(); // Attempt remediation. if ($remediate && !$response->isSuccessful()) { $log->info("\xE2\x9A\xA0 Remediating " . $policy->get('title')); $response = $sandbox->remediate(); } if ($is_progress_bar) { $log->advance(); } } return $this; }
php
public function assessTarget(TargetInterface $target, array $policies, \DateTime $start = NULL, \DateTime $end = NULL, $remediate = FALSE) { $start = $start ?: new \DateTime('-1 day'); $end = $end ?: new \DateTime(); $policies = array_filter($policies, function ($policy) { return $policy instanceof Policy; }); $log = Container::getLogger(); $is_progress_bar = $log instanceof ProgressBar; foreach ($policies as $policy) { if ($is_progress_bar) { $log->setTopic($this->uri . '][' . $policy->get('title')); } $log->info("Assessing policy..."); // Setup the sandbox to run the assessment. $sandbox = new Sandbox($target, $policy, $this); $sandbox->setReportingPeriod($start, $end); $response = $sandbox->run(); // Attempt remediation. if ($remediate && !$response->isSuccessful()) { $log->info("\xE2\x9A\xA0 Remediating " . $policy->get('title')); $response = $sandbox->remediate(); } if ($is_progress_bar) { $log->advance(); } } return $this; }
[ "public", "function", "assessTarget", "(", "TargetInterface", "$", "target", ",", "array", "$", "policies", ",", "\\", "DateTime", "$", "start", "=", "NULL", ",", "\\", "DateTime", "$", "end", "=", "NULL", ",", "$", "remediate", "=", "FALSE", ")", "{", "$", "start", "=", "$", "start", "?", ":", "new", "\\", "DateTime", "(", "'-1 day'", ")", ";", "$", "end", "=", "$", "end", "?", ":", "new", "\\", "DateTime", "(", ")", ";", "$", "policies", "=", "array_filter", "(", "$", "policies", ",", "function", "(", "$", "policy", ")", "{", "return", "$", "policy", "instanceof", "Policy", ";", "}", ")", ";", "$", "log", "=", "Container", "::", "getLogger", "(", ")", ";", "$", "is_progress_bar", "=", "$", "log", "instanceof", "ProgressBar", ";", "foreach", "(", "$", "policies", "as", "$", "policy", ")", "{", "if", "(", "$", "is_progress_bar", ")", "{", "$", "log", "->", "setTopic", "(", "$", "this", "->", "uri", ".", "']['", ".", "$", "policy", "->", "get", "(", "'title'", ")", ")", ";", "}", "$", "log", "->", "info", "(", "\"Assessing policy...\"", ")", ";", "// Setup the sandbox to run the assessment.", "$", "sandbox", "=", "new", "Sandbox", "(", "$", "target", ",", "$", "policy", ",", "$", "this", ")", ";", "$", "sandbox", "->", "setReportingPeriod", "(", "$", "start", ",", "$", "end", ")", ";", "$", "response", "=", "$", "sandbox", "->", "run", "(", ")", ";", "// Attempt remediation.", "if", "(", "$", "remediate", "&&", "!", "$", "response", "->", "isSuccessful", "(", ")", ")", "{", "$", "log", "->", "info", "(", "\"\\xE2\\x9A\\xA0 Remediating \"", ".", "$", "policy", "->", "get", "(", "'title'", ")", ")", ";", "$", "response", "=", "$", "sandbox", "->", "remediate", "(", ")", ";", "}", "if", "(", "$", "is_progress_bar", ")", "{", "$", "log", "->", "advance", "(", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Assess a Target. @param TargetInterface $target @param array $policies each item should be a Drutiny\Policy object. @param DateTime $start The start date of the reporting period. Defaults to -1 day. @param DateTime $end The end date of the reporting period. Defaults to now. @param bool $remediate If an Drutiny\Audit supports remediation and the policy failes, remediate the policy. Defaults to FALSE.
[ "Assess", "a", "Target", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Assessment.php#L39-L76
drutiny/drutiny
src/Assessment.php
Assessment.setPolicyResult
public function setPolicyResult(AuditResponse $response) { $this->results[$response->getPolicy()->get('name')] = $response; // Set the overall success state of the Assessment. Considered // a success if all policies pass. $this->successful = $this->successful && $response->isSuccessful(); // If the policy failed its assessment and the severity of the Policy // is higher than the current severity of the assessment, then increase // the severity of the overall assessment. $severity = $response->getPolicy()->getSeverity(); if (!$response->isSuccessful() && ($this->severity < $severity)) { $this->setSeverity($severity); } }
php
public function setPolicyResult(AuditResponse $response) { $this->results[$response->getPolicy()->get('name')] = $response; // Set the overall success state of the Assessment. Considered // a success if all policies pass. $this->successful = $this->successful && $response->isSuccessful(); // If the policy failed its assessment and the severity of the Policy // is higher than the current severity of the assessment, then increase // the severity of the overall assessment. $severity = $response->getPolicy()->getSeverity(); if (!$response->isSuccessful() && ($this->severity < $severity)) { $this->setSeverity($severity); } }
[ "public", "function", "setPolicyResult", "(", "AuditResponse", "$", "response", ")", "{", "$", "this", "->", "results", "[", "$", "response", "->", "getPolicy", "(", ")", "->", "get", "(", "'name'", ")", "]", "=", "$", "response", ";", "// Set the overall success state of the Assessment. Considered", "// a success if all policies pass.", "$", "this", "->", "successful", "=", "$", "this", "->", "successful", "&&", "$", "response", "->", "isSuccessful", "(", ")", ";", "// If the policy failed its assessment and the severity of the Policy", "// is higher than the current severity of the assessment, then increase", "// the severity of the overall assessment.", "$", "severity", "=", "$", "response", "->", "getPolicy", "(", ")", "->", "getSeverity", "(", ")", ";", "if", "(", "!", "$", "response", "->", "isSuccessful", "(", ")", "&&", "(", "$", "this", "->", "severity", "<", "$", "severity", ")", ")", "{", "$", "this", "->", "setSeverity", "(", "$", "severity", ")", ";", "}", "}" ]
Set the result of a Policy. The result of a Policy is unique to an assessment result set. @param AuditResponse $response
[ "Set", "the", "result", "of", "a", "Policy", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Assessment.php#L85-L100
drutiny/drutiny
src/Assessment.php
Assessment.getPolicyResult
public function getPolicyResult($name) { if (!isset($this->results[$name])) { throw new NoAuditResponseFoundException($name, "Policy '$name' does not have an AuditResponse."); } return $this->results[$name]; }
php
public function getPolicyResult($name) { if (!isset($this->results[$name])) { throw new NoAuditResponseFoundException($name, "Policy '$name' does not have an AuditResponse."); } return $this->results[$name]; }
[ "public", "function", "getPolicyResult", "(", "$", "name", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "results", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "NoAuditResponseFoundException", "(", "$", "name", ",", "\"Policy '$name' does not have an AuditResponse.\"", ")", ";", "}", "return", "$", "this", "->", "results", "[", "$", "name", "]", ";", "}" ]
Get an AuditResponse object by Policy name. @param string $name @return AuditResponse
[ "Get", "an", "AuditResponse", "object", "by", "Policy", "name", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Assessment.php#L115-L121
drutiny/drutiny
src/PolicySource/DrutinyGitHubIO.php
DrutinyGitHubIO.getList
public function getList() { $api = new Api(); $list = []; foreach ($api->getPolicyList() as $listedPolicy) { $list[$listedPolicy['name']] = $listedPolicy; } return $list; }
php
public function getList() { $api = new Api(); $list = []; foreach ($api->getPolicyList() as $listedPolicy) { $list[$listedPolicy['name']] = $listedPolicy; } return $list; }
[ "public", "function", "getList", "(", ")", "{", "$", "api", "=", "new", "Api", "(", ")", ";", "$", "list", "=", "[", "]", ";", "foreach", "(", "$", "api", "->", "getPolicyList", "(", ")", "as", "$", "listedPolicy", ")", "{", "$", "list", "[", "$", "listedPolicy", "[", "'name'", "]", "]", "=", "$", "listedPolicy", ";", "}", "return", "$", "list", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/PolicySource/DrutinyGitHubIO.php#L22-L30
drutiny/drutiny
src/PolicySource/DrutinyGitHubIO.php
DrutinyGitHubIO.load
public function load(array $definition) { $cache = Container::cache('drutiny.github.io.policy'); $item = $cache->getItem($definition['signature']); if ($item->isHit()) { Container::getLogger()->info("Cache hit for {$definition['name']} from " . $this->getName()); return new Policy($item->get()); } Container::getLogger()->info("Fetching {$definition['name']} from {Api::BaseUrl}"); $endpoint = str_replace(parse_url(Api::BaseUrl, PHP_URL_PATH), '', $definition['_links']['self']['href']); $policyData = json_decode(Api::getClient()->get($endpoint)->getBody(), TRUE); $policyData['filepath'] = $definition['_links']['self']['href']; $item->set($policyData) // The cache ID (signature) is a hash that changes when the policy // metadata changes so we can cache this as long as we like. ->expiresAt(new \DateTime('+1 month')); $cache->save($item); return new Policy($policyData); }
php
public function load(array $definition) { $cache = Container::cache('drutiny.github.io.policy'); $item = $cache->getItem($definition['signature']); if ($item->isHit()) { Container::getLogger()->info("Cache hit for {$definition['name']} from " . $this->getName()); return new Policy($item->get()); } Container::getLogger()->info("Fetching {$definition['name']} from {Api::BaseUrl}"); $endpoint = str_replace(parse_url(Api::BaseUrl, PHP_URL_PATH), '', $definition['_links']['self']['href']); $policyData = json_decode(Api::getClient()->get($endpoint)->getBody(), TRUE); $policyData['filepath'] = $definition['_links']['self']['href']; $item->set($policyData) // The cache ID (signature) is a hash that changes when the policy // metadata changes so we can cache this as long as we like. ->expiresAt(new \DateTime('+1 month')); $cache->save($item); return new Policy($policyData); }
[ "public", "function", "load", "(", "array", "$", "definition", ")", "{", "$", "cache", "=", "Container", "::", "cache", "(", "'drutiny.github.io.policy'", ")", ";", "$", "item", "=", "$", "cache", "->", "getItem", "(", "$", "definition", "[", "'signature'", "]", ")", ";", "if", "(", "$", "item", "->", "isHit", "(", ")", ")", "{", "Container", "::", "getLogger", "(", ")", "->", "info", "(", "\"Cache hit for {$definition['name']} from \"", ".", "$", "this", "->", "getName", "(", ")", ")", ";", "return", "new", "Policy", "(", "$", "item", "->", "get", "(", ")", ")", ";", "}", "Container", "::", "getLogger", "(", ")", "->", "info", "(", "\"Fetching {$definition['name']} from {Api::BaseUrl}\"", ")", ";", "$", "endpoint", "=", "str_replace", "(", "parse_url", "(", "Api", "::", "BaseUrl", ",", "PHP_URL_PATH", ")", ",", "''", ",", "$", "definition", "[", "'_links'", "]", "[", "'self'", "]", "[", "'href'", "]", ")", ";", "$", "policyData", "=", "json_decode", "(", "Api", "::", "getClient", "(", ")", "->", "get", "(", "$", "endpoint", ")", "->", "getBody", "(", ")", ",", "TRUE", ")", ";", "$", "policyData", "[", "'filepath'", "]", "=", "$", "definition", "[", "'_links'", "]", "[", "'self'", "]", "[", "'href'", "]", ";", "$", "item", "->", "set", "(", "$", "policyData", ")", "// The cache ID (signature) is a hash that changes when the policy", "// metadata changes so we can cache this as long as we like.", "->", "expiresAt", "(", "new", "\\", "DateTime", "(", "'+1 month'", ")", ")", ";", "$", "cache", "->", "save", "(", "$", "item", ")", ";", "return", "new", "Policy", "(", "$", "policyData", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/PolicySource/DrutinyGitHubIO.php#L35-L57
drutiny/drutiny
src/Audit/Database/DatabaseSize.php
DatabaseSize.audit
public function audit(Sandbox $sandbox) { $stat = $sandbox->drush(['format' => 'json']) ->status(); $name = $stat['db-name']; $sql = "SELECT ROUND(SUM(data_length + index_length) / 1024 / 1024, 1) 'DB Size in MB' FROM information_schema.tables WHERE table_schema='{$name}' GROUP BY table_schema;"; $resultLines = $sandbox->drush()->sqlq($sql); $resultLines = array_filter($resultLines, function($line) { return $line !== 'DB Size in MB'; }); $size = (float) reset($resultLines); $sandbox->setParameter('db', $name) ->setParameter('size', $size); if ($sandbox->getParameter('max_size') < $size) { return FALSE; } if ($sandbox->getParameter('warning_size') < $size) { return Audit::WARNING; } return TRUE; }
php
public function audit(Sandbox $sandbox) { $stat = $sandbox->drush(['format' => 'json']) ->status(); $name = $stat['db-name']; $sql = "SELECT ROUND(SUM(data_length + index_length) / 1024 / 1024, 1) 'DB Size in MB' FROM information_schema.tables WHERE table_schema='{$name}' GROUP BY table_schema;"; $resultLines = $sandbox->drush()->sqlq($sql); $resultLines = array_filter($resultLines, function($line) { return $line !== 'DB Size in MB'; }); $size = (float) reset($resultLines); $sandbox->setParameter('db', $name) ->setParameter('size', $size); if ($sandbox->getParameter('max_size') < $size) { return FALSE; } if ($sandbox->getParameter('warning_size') < $size) { return Audit::WARNING; } return TRUE; }
[ "public", "function", "audit", "(", "Sandbox", "$", "sandbox", ")", "{", "$", "stat", "=", "$", "sandbox", "->", "drush", "(", "[", "'format'", "=>", "'json'", "]", ")", "->", "status", "(", ")", ";", "$", "name", "=", "$", "stat", "[", "'db-name'", "]", ";", "$", "sql", "=", "\"SELECT ROUND(SUM(data_length + index_length) / 1024 / 1024, 1) 'DB Size in MB'\n FROM information_schema.tables\n WHERE table_schema='{$name}'\n GROUP BY table_schema;\"", ";", "$", "resultLines", "=", "$", "sandbox", "->", "drush", "(", ")", "->", "sqlq", "(", "$", "sql", ")", ";", "$", "resultLines", "=", "array_filter", "(", "$", "resultLines", ",", "function", "(", "$", "line", ")", "{", "return", "$", "line", "!==", "'DB Size in MB'", ";", "}", ")", ";", "$", "size", "=", "(", "float", ")", "reset", "(", "$", "resultLines", ")", ";", "$", "sandbox", "->", "setParameter", "(", "'db'", ",", "$", "name", ")", "->", "setParameter", "(", "'size'", ",", "$", "size", ")", ";", "if", "(", "$", "sandbox", "->", "getParameter", "(", "'max_size'", ")", "<", "$", "size", ")", "{", "return", "FALSE", ";", "}", "if", "(", "$", "sandbox", "->", "getParameter", "(", "'warning_size'", ")", "<", "$", "size", ")", "{", "return", "Audit", "::", "WARNING", ";", "}", "return", "TRUE", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Audit/Database/DatabaseSize.php#L39-L67
drutiny/drutiny
src/Policy/PolicyBase.php
PolicyBase.render
protected function render($markdown, $replacements) { $m = new \Mustache_Engine(); try { return $m->render($markdown, $replacements); } catch (\Mustache_Exception $e) { throw new \Exception("Error in $this->name: " . $e->getMessage()); } }
php
protected function render($markdown, $replacements) { $m = new \Mustache_Engine(); try { return $m->render($markdown, $replacements); } catch (\Mustache_Exception $e) { throw new \Exception("Error in $this->name: " . $e->getMessage()); } }
[ "protected", "function", "render", "(", "$", "markdown", ",", "$", "replacements", ")", "{", "$", "m", "=", "new", "\\", "Mustache_Engine", "(", ")", ";", "try", "{", "return", "$", "m", "->", "render", "(", "$", "markdown", ",", "$", "replacements", ")", ";", "}", "catch", "(", "\\", "Mustache_Exception", "$", "e", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Error in $this->name: \"", ".", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "}" ]
Render a property.
[ "Render", "a", "property", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Policy/PolicyBase.php#L75-L83
drutiny/drutiny
src/Policy/PolicyBase.php
PolicyBase.get
public function get($property, $replacements = []) { if (!isset($this->{$property})) { throw new \Exception("Attempt to retrieve unknown property: $property. Available properties: \n" . print_r((array) $this, 1)); } if (in_array($property, $this->renderableProperties)) { return $this->render($this->{$property}, $replacements); } return $this->{$property}; }
php
public function get($property, $replacements = []) { if (!isset($this->{$property})) { throw new \Exception("Attempt to retrieve unknown property: $property. Available properties: \n" . print_r((array) $this, 1)); } if (in_array($property, $this->renderableProperties)) { return $this->render($this->{$property}, $replacements); } return $this->{$property}; }
[ "public", "function", "get", "(", "$", "property", ",", "$", "replacements", "=", "[", "]", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "{", "$", "property", "}", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Attempt to retrieve unknown property: $property. Available properties: \\n\"", ".", "print_r", "(", "(", "array", ")", "$", "this", ",", "1", ")", ")", ";", "}", "if", "(", "in_array", "(", "$", "property", ",", "$", "this", "->", "renderableProperties", ")", ")", "{", "return", "$", "this", "->", "render", "(", "$", "this", "->", "{", "$", "property", "}", ",", "$", "replacements", ")", ";", "}", "return", "$", "this", "->", "{", "$", "property", "}", ";", "}" ]
Retrieve a property value and token replacement.
[ "Retrieve", "a", "property", "value", "and", "token", "replacement", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Policy/PolicyBase.php#L88-L96
drutiny/drutiny
src/Driver/DrushHelper.php
DrushHelper.variable_get
public function variable_get($name, $default = NULL) { $vars = $this->drush->setDrushOptions(['format' => 'json'])->variableGet(); if (!isset($vars[$name])) { return $default; } return $vars[$name]; }
php
public function variable_get($name, $default = NULL) { $vars = $this->drush->setDrushOptions(['format' => 'json'])->variableGet(); if (!isset($vars[$name])) { return $default; } return $vars[$name]; }
[ "public", "function", "variable_get", "(", "$", "name", ",", "$", "default", "=", "NULL", ")", "{", "$", "vars", "=", "$", "this", "->", "drush", "->", "setDrushOptions", "(", "[", "'format'", "=>", "'json'", "]", ")", "->", "variableGet", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "vars", "[", "$", "name", "]", ")", ")", "{", "return", "$", "default", ";", "}", "return", "$", "vars", "[", "$", "name", "]", ";", "}" ]
Function like the Drupal 7 variable_get function. @param $name The name of the variable (exact). @param mixed $default The value to return if the variable is not set.
[ "Function", "like", "the", "Drupal", "7", "variable_get", "function", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Driver/DrushHelper.php#L25-L32
drutiny/drutiny
src/Profile/ProfileSource.php
ProfileSource.loadProfileByName
public static function loadProfileByName($name) { $list = self::getProfileList(); $definition = $list[$name]; return self::getSource($definition['source'])->load($definition); }
php
public static function loadProfileByName($name) { $list = self::getProfileList(); $definition = $list[$name]; return self::getSource($definition['source'])->load($definition); }
[ "public", "static", "function", "loadProfileByName", "(", "$", "name", ")", "{", "$", "list", "=", "self", "::", "getProfileList", "(", ")", ";", "$", "definition", "=", "$", "list", "[", "$", "name", "]", ";", "return", "self", "::", "getSource", "(", "$", "definition", "[", "'source'", "]", ")", "->", "load", "(", "$", "definition", ")", ";", "}" ]
Load policy by name. @param $name string
[ "Load", "policy", "by", "name", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Profile/ProfileSource.php#L15-L21
drutiny/drutiny
src/Profile/ProfileSource.php
ProfileSource.getProfileList
public static function getProfileList() { static $list; if (!empty($list)) { return $list; } $lists = array_map(function ($source) { return array_map(function ($item) use ($source) { $item['source'] = $source->getName(); return $item; }, $source->getList()); }, self::getSources()); $list = call_user_func_array('array_merge', $lists); return $list; }
php
public static function getProfileList() { static $list; if (!empty($list)) { return $list; } $lists = array_map(function ($source) { return array_map(function ($item) use ($source) { $item['source'] = $source->getName(); return $item; }, $source->getList()); }, self::getSources()); $list = call_user_func_array('array_merge', $lists); return $list; }
[ "public", "static", "function", "getProfileList", "(", ")", "{", "static", "$", "list", ";", "if", "(", "!", "empty", "(", "$", "list", ")", ")", "{", "return", "$", "list", ";", "}", "$", "lists", "=", "array_map", "(", "function", "(", "$", "source", ")", "{", "return", "array_map", "(", "function", "(", "$", "item", ")", "use", "(", "$", "source", ")", "{", "$", "item", "[", "'source'", "]", "=", "$", "source", "->", "getName", "(", ")", ";", "return", "$", "item", ";", "}", ",", "$", "source", "->", "getList", "(", ")", ")", ";", "}", ",", "self", "::", "getSources", "(", ")", ")", ";", "$", "list", "=", "call_user_func_array", "(", "'array_merge'", ",", "$", "lists", ")", ";", "return", "$", "list", ";", "}" ]
Acquire a list of available policies. @return array of policy information arrays.
[ "Acquire", "a", "list", "of", "available", "policies", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Profile/ProfileSource.php#L28-L45
drutiny/drutiny
src/Profile/ProfileSource.php
ProfileSource.loadAll
public static function loadAll() { $list = []; foreach (self::getProfileList() as $definition) { $list[$definition['name']] = self::loadProfileByName($definition['name']); } return $list; }
php
public static function loadAll() { $list = []; foreach (self::getProfileList() as $definition) { $list[$definition['name']] = self::loadProfileByName($definition['name']); } return $list; }
[ "public", "static", "function", "loadAll", "(", ")", "{", "$", "list", "=", "[", "]", ";", "foreach", "(", "self", "::", "getProfileList", "(", ")", "as", "$", "definition", ")", "{", "$", "list", "[", "$", "definition", "[", "'name'", "]", "]", "=", "self", "::", "loadProfileByName", "(", "$", "definition", "[", "'name'", "]", ")", ";", "}", "return", "$", "list", ";", "}" ]
Load all policies as loaded Policy objects.
[ "Load", "all", "policies", "as", "loaded", "Policy", "objects", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Profile/ProfileSource.php#L50-L57
drutiny/drutiny
src/Profile/ProfileSource.php
ProfileSource.getSources
public static function getSources() { $item = Container::cache(__CLASS__)->getItem('sources'); if ($item->isHit()) { return $item->get(); } // The PolicySource config directive loads in class names that provides // policies for Drutiny to use. We need to validate each provided source // implements PolicySourceInterface. $sources = array_filter(array_map(function ($class) { $object = new $class(); if (!($object instanceof ProfileSourceInterface)) { return false; } return $object; }, Config::get('ProfileSource'))); // If multiple sources provide the same policy by name, then the policy from // the first source in the list will by used. usort($sources, function ($a, $b) { if ($a->getWeight() == $b->getWeight()) { return 0; } return $a->getWeight() > $b->getWeight() ? 1 : -1; }); Container::cache(__CLASS__)->save( $item->set($sources)->expiresAfter(3600) ); return $sources; }
php
public static function getSources() { $item = Container::cache(__CLASS__)->getItem('sources'); if ($item->isHit()) { return $item->get(); } // The PolicySource config directive loads in class names that provides // policies for Drutiny to use. We need to validate each provided source // implements PolicySourceInterface. $sources = array_filter(array_map(function ($class) { $object = new $class(); if (!($object instanceof ProfileSourceInterface)) { return false; } return $object; }, Config::get('ProfileSource'))); // If multiple sources provide the same policy by name, then the policy from // the first source in the list will by used. usort($sources, function ($a, $b) { if ($a->getWeight() == $b->getWeight()) { return 0; } return $a->getWeight() > $b->getWeight() ? 1 : -1; }); Container::cache(__CLASS__)->save( $item->set($sources)->expiresAfter(3600) ); return $sources; }
[ "public", "static", "function", "getSources", "(", ")", "{", "$", "item", "=", "Container", "::", "cache", "(", "__CLASS__", ")", "->", "getItem", "(", "'sources'", ")", ";", "if", "(", "$", "item", "->", "isHit", "(", ")", ")", "{", "return", "$", "item", "->", "get", "(", ")", ";", "}", "// The PolicySource config directive loads in class names that provides", "// policies for Drutiny to use. We need to validate each provided source", "// implements PolicySourceInterface.", "$", "sources", "=", "array_filter", "(", "array_map", "(", "function", "(", "$", "class", ")", "{", "$", "object", "=", "new", "$", "class", "(", ")", ";", "if", "(", "!", "(", "$", "object", "instanceof", "ProfileSourceInterface", ")", ")", "{", "return", "false", ";", "}", "return", "$", "object", ";", "}", ",", "Config", "::", "get", "(", "'ProfileSource'", ")", ")", ")", ";", "// If multiple sources provide the same policy by name, then the policy from", "// the first source in the list will by used.", "usort", "(", "$", "sources", ",", "function", "(", "$", "a", ",", "$", "b", ")", "{", "if", "(", "$", "a", "->", "getWeight", "(", ")", "==", "$", "b", "->", "getWeight", "(", ")", ")", "{", "return", "0", ";", "}", "return", "$", "a", "->", "getWeight", "(", ")", ">", "$", "b", "->", "getWeight", "(", ")", "?", "1", ":", "-", "1", ";", "}", ")", ";", "Container", "::", "cache", "(", "__CLASS__", ")", "->", "save", "(", "$", "item", "->", "set", "(", "$", "sources", ")", "->", "expiresAfter", "(", "3600", ")", ")", ";", "return", "$", "sources", ";", "}" ]
Load the sources that provide policies. @return array of PolicySourceInterface objects.
[ "Load", "the", "sources", "that", "provide", "policies", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Profile/ProfileSource.php#L64-L95
drutiny/drutiny
src/Profile/ProfileSource.php
ProfileSource.getSource
public static function getSource($name) { foreach (self::getSources() as $source) { if ($source->getName() == $name) { return $source; } } throw new \Exception("ProfileSource not found: $name."); }
php
public static function getSource($name) { foreach (self::getSources() as $source) { if ($source->getName() == $name) { return $source; } } throw new \Exception("ProfileSource not found: $name."); }
[ "public", "static", "function", "getSource", "(", "$", "name", ")", "{", "foreach", "(", "self", "::", "getSources", "(", ")", "as", "$", "source", ")", "{", "if", "(", "$", "source", "->", "getName", "(", ")", "==", "$", "name", ")", "{", "return", "$", "source", ";", "}", "}", "throw", "new", "\\", "Exception", "(", "\"ProfileSource not found: $name.\"", ")", ";", "}" ]
Load a single source.
[ "Load", "a", "single", "source", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Profile/ProfileSource.php#L100-L108
drutiny/drutiny
src/Sandbox/ParameterTrait.php
ParameterTrait.getParameter
public function getParameter($key, $default_value = NULL) { if (isset($this->params[$key])) { return $this->params[$key]; } $defaults = $this->sandbox() ->getPolicy() ->getParameterDefaults(); if (isset($defaults[$key])) { $default_value = $defaults[$key]; } // Ensure default values are recorded for use as tokens. $this->setParameter($key, $default_value); return $default_value; }
php
public function getParameter($key, $default_value = NULL) { if (isset($this->params[$key])) { return $this->params[$key]; } $defaults = $this->sandbox() ->getPolicy() ->getParameterDefaults(); if (isset($defaults[$key])) { $default_value = $defaults[$key]; } // Ensure default values are recorded for use as tokens. $this->setParameter($key, $default_value); return $default_value; }
[ "public", "function", "getParameter", "(", "$", "key", ",", "$", "default_value", "=", "NULL", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "params", "[", "$", "key", "]", ")", ")", "{", "return", "$", "this", "->", "params", "[", "$", "key", "]", ";", "}", "$", "defaults", "=", "$", "this", "->", "sandbox", "(", ")", "->", "getPolicy", "(", ")", "->", "getParameterDefaults", "(", ")", ";", "if", "(", "isset", "(", "$", "defaults", "[", "$", "key", "]", ")", ")", "{", "$", "default_value", "=", "$", "defaults", "[", "$", "key", "]", ";", "}", "// Ensure default values are recorded for use as tokens.", "$", "this", "->", "setParameter", "(", "$", "key", ",", "$", "default_value", ")", ";", "return", "$", "default_value", ";", "}" ]
Expose parameters to the check.
[ "Expose", "parameters", "to", "the", "check", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Sandbox/ParameterTrait.php#L18-L34
drutiny/drutiny
src/Container.php
Container.getVerbosity
public static function getVerbosity() { if (!isset(self::$verbosity)) { switch (getenv('SHELL_VERBOSITY')) { case -1: return OutputInterface::VERBOSITY_QUIET; break; case 1: return OutputInterface::VERBOSITY_VERBOSE; break; case 2: return OutputInterface::VERBOSITY_VERY_VERBOSE; break; case 3: return OutputInterface::VERBOSITY_DEBUG; break; default: return OutputInterface::VERBOSITY_NORMAL; break; } } return self::$verbosity; }
php
public static function getVerbosity() { if (!isset(self::$verbosity)) { switch (getenv('SHELL_VERBOSITY')) { case -1: return OutputInterface::VERBOSITY_QUIET; break; case 1: return OutputInterface::VERBOSITY_VERBOSE; break; case 2: return OutputInterface::VERBOSITY_VERY_VERBOSE; break; case 3: return OutputInterface::VERBOSITY_DEBUG; break; default: return OutputInterface::VERBOSITY_NORMAL; break; } } return self::$verbosity; }
[ "public", "static", "function", "getVerbosity", "(", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "verbosity", ")", ")", "{", "switch", "(", "getenv", "(", "'SHELL_VERBOSITY'", ")", ")", "{", "case", "-", "1", ":", "return", "OutputInterface", "::", "VERBOSITY_QUIET", ";", "break", ";", "case", "1", ":", "return", "OutputInterface", "::", "VERBOSITY_VERBOSE", ";", "break", ";", "case", "2", ":", "return", "OutputInterface", "::", "VERBOSITY_VERY_VERBOSE", ";", "break", ";", "case", "3", ":", "return", "OutputInterface", "::", "VERBOSITY_DEBUG", ";", "break", ";", "default", ":", "return", "OutputInterface", "::", "VERBOSITY_NORMAL", ";", "break", ";", "}", "}", "return", "self", "::", "$", "verbosity", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Container.php#L72-L84
drutiny/drutiny
src/Sandbox/Sandbox.php
Sandbox.run
public function run() { $response = new AuditResponse($this->getPolicy()); $watchdog = Container::getLogger(); $watchdog->info('Auditing ' . $this->getPolicy()->get('name')); try { // Ensure policy dependencies are met. foreach ($this->getPolicy()->getDepends() as $dependency) { // Throws DependencyException if dependency is not met. $dependency->execute($this); } // Run the audit over the policy. $outcome = $this->getAuditor()->execute($this); // Log the parameters output. $watchdog->debug("Tokens:\n" . Yaml::dump($this->getParameterTokens(), 4)); // Set the response. $response->set($outcome, $this->getParameterTokens()); } catch (\Drutiny\Policy\DependencyException $e) { $this->setParameter('exception', $e->getMessage()); $response->set($e->getDependency()->getFailBehaviour(), $this->getParameterTokens()); } catch (\Drutiny\AuditValidationException $e) { $this->setParameter('exception', $e->getMessage()); $watchdog->warning($e->getMessage()); $response->set(Audit::NOT_APPLICABLE, $this->getParameterTokens()); } catch (\Exception $e) { $message = $e->getMessage(); if (Container::getVerbosity() > OutputInterface::VERBOSITY_NORMAL) { $message .= PHP_EOL . $e->getTraceAsString(); } $this->setParameter('exception', $message); $response->set(Audit::ERROR, $this->getParameterTokens()); } // Omit irrelevant AuditResponses. if (!$response->isIrrelevant()) { $this->getAssessment()->setPolicyResult($response); } return $response; }
php
public function run() { $response = new AuditResponse($this->getPolicy()); $watchdog = Container::getLogger(); $watchdog->info('Auditing ' . $this->getPolicy()->get('name')); try { // Ensure policy dependencies are met. foreach ($this->getPolicy()->getDepends() as $dependency) { // Throws DependencyException if dependency is not met. $dependency->execute($this); } // Run the audit over the policy. $outcome = $this->getAuditor()->execute($this); // Log the parameters output. $watchdog->debug("Tokens:\n" . Yaml::dump($this->getParameterTokens(), 4)); // Set the response. $response->set($outcome, $this->getParameterTokens()); } catch (\Drutiny\Policy\DependencyException $e) { $this->setParameter('exception', $e->getMessage()); $response->set($e->getDependency()->getFailBehaviour(), $this->getParameterTokens()); } catch (\Drutiny\AuditValidationException $e) { $this->setParameter('exception', $e->getMessage()); $watchdog->warning($e->getMessage()); $response->set(Audit::NOT_APPLICABLE, $this->getParameterTokens()); } catch (\Exception $e) { $message = $e->getMessage(); if (Container::getVerbosity() > OutputInterface::VERBOSITY_NORMAL) { $message .= PHP_EOL . $e->getTraceAsString(); } $this->setParameter('exception', $message); $response->set(Audit::ERROR, $this->getParameterTokens()); } // Omit irrelevant AuditResponses. if (!$response->isIrrelevant()) { $this->getAssessment()->setPolicyResult($response); } return $response; }
[ "public", "function", "run", "(", ")", "{", "$", "response", "=", "new", "AuditResponse", "(", "$", "this", "->", "getPolicy", "(", ")", ")", ";", "$", "watchdog", "=", "Container", "::", "getLogger", "(", ")", ";", "$", "watchdog", "->", "info", "(", "'Auditing '", ".", "$", "this", "->", "getPolicy", "(", ")", "->", "get", "(", "'name'", ")", ")", ";", "try", "{", "// Ensure policy dependencies are met.", "foreach", "(", "$", "this", "->", "getPolicy", "(", ")", "->", "getDepends", "(", ")", "as", "$", "dependency", ")", "{", "// Throws DependencyException if dependency is not met.", "$", "dependency", "->", "execute", "(", "$", "this", ")", ";", "}", "// Run the audit over the policy.", "$", "outcome", "=", "$", "this", "->", "getAuditor", "(", ")", "->", "execute", "(", "$", "this", ")", ";", "// Log the parameters output.", "$", "watchdog", "->", "debug", "(", "\"Tokens:\\n\"", ".", "Yaml", "::", "dump", "(", "$", "this", "->", "getParameterTokens", "(", ")", ",", "4", ")", ")", ";", "// Set the response.", "$", "response", "->", "set", "(", "$", "outcome", ",", "$", "this", "->", "getParameterTokens", "(", ")", ")", ";", "}", "catch", "(", "\\", "Drutiny", "\\", "Policy", "\\", "DependencyException", "$", "e", ")", "{", "$", "this", "->", "setParameter", "(", "'exception'", ",", "$", "e", "->", "getMessage", "(", ")", ")", ";", "$", "response", "->", "set", "(", "$", "e", "->", "getDependency", "(", ")", "->", "getFailBehaviour", "(", ")", ",", "$", "this", "->", "getParameterTokens", "(", ")", ")", ";", "}", "catch", "(", "\\", "Drutiny", "\\", "AuditValidationException", "$", "e", ")", "{", "$", "this", "->", "setParameter", "(", "'exception'", ",", "$", "e", "->", "getMessage", "(", ")", ")", ";", "$", "watchdog", "->", "warning", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "$", "response", "->", "set", "(", "Audit", "::", "NOT_APPLICABLE", ",", "$", "this", "->", "getParameterTokens", "(", ")", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "message", "=", "$", "e", "->", "getMessage", "(", ")", ";", "if", "(", "Container", "::", "getVerbosity", "(", ")", ">", "OutputInterface", "::", "VERBOSITY_NORMAL", ")", "{", "$", "message", ".=", "PHP_EOL", ".", "$", "e", "->", "getTraceAsString", "(", ")", ";", "}", "$", "this", "->", "setParameter", "(", "'exception'", ",", "$", "message", ")", ";", "$", "response", "->", "set", "(", "Audit", "::", "ERROR", ",", "$", "this", "->", "getParameterTokens", "(", ")", ")", ";", "}", "// Omit irrelevant AuditResponses.", "if", "(", "!", "$", "response", "->", "isIrrelevant", "(", ")", ")", "{", "$", "this", "->", "getAssessment", "(", ")", "->", "setPolicyResult", "(", "$", "response", ")", ";", "}", "return", "$", "response", ";", "}" ]
Run the check and capture the outcomes.
[ "Run", "the", "check", "and", "capture", "the", "outcomes", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Sandbox/Sandbox.php#L80-L125
drutiny/drutiny
src/Sandbox/Sandbox.php
Sandbox.remediate
public function remediate() { $response = new AuditResponse($this->getPolicy()); try { // Do not attempt remediation on checks that don't support it. if (!($this->getAuditor() instanceof RemediableInterface)) { throw new \Exception(get_class($this->getAuditor()) . ' is not remediable.'); } // Make sure remediation does report false positives due to caching. Cache::purge(); $outcome = $this->getAuditor()->remediate($this); $response->set($outcome, $this->getParameterTokens()); } catch (\Exception $e) { $this->setParameter('exception', $e->getMessage()); $response->set(Audit::ERROR, $this->getParameterTokens()); } $this->getAssessment()->setPolicyResult($response); return $response; }
php
public function remediate() { $response = new AuditResponse($this->getPolicy()); try { // Do not attempt remediation on checks that don't support it. if (!($this->getAuditor() instanceof RemediableInterface)) { throw new \Exception(get_class($this->getAuditor()) . ' is not remediable.'); } // Make sure remediation does report false positives due to caching. Cache::purge(); $outcome = $this->getAuditor()->remediate($this); $response->set($outcome, $this->getParameterTokens()); } catch (\Exception $e) { $this->setParameter('exception', $e->getMessage()); $response->set(Audit::ERROR, $this->getParameterTokens()); } $this->getAssessment()->setPolicyResult($response); return $response; }
[ "public", "function", "remediate", "(", ")", "{", "$", "response", "=", "new", "AuditResponse", "(", "$", "this", "->", "getPolicy", "(", ")", ")", ";", "try", "{", "// Do not attempt remediation on checks that don't support it.", "if", "(", "!", "(", "$", "this", "->", "getAuditor", "(", ")", "instanceof", "RemediableInterface", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "get_class", "(", "$", "this", "->", "getAuditor", "(", ")", ")", ".", "' is not remediable.'", ")", ";", "}", "// Make sure remediation does report false positives due to caching.", "Cache", "::", "purge", "(", ")", ";", "$", "outcome", "=", "$", "this", "->", "getAuditor", "(", ")", "->", "remediate", "(", "$", "this", ")", ";", "$", "response", "->", "set", "(", "$", "outcome", ",", "$", "this", "->", "getParameterTokens", "(", ")", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "setParameter", "(", "'exception'", ",", "$", "e", "->", "getMessage", "(", ")", ")", ";", "$", "response", "->", "set", "(", "Audit", "::", "ERROR", ",", "$", "this", "->", "getParameterTokens", "(", ")", ")", ";", "}", "$", "this", "->", "getAssessment", "(", ")", "->", "setPolicyResult", "(", "$", "response", ")", ";", "return", "$", "response", ";", "}" ]
Remediate the check if available.
[ "Remediate", "the", "check", "if", "available", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Sandbox/Sandbox.php#L130-L151
drutiny/drutiny
src/Report/Format.php
Format.renderTemplate
public function renderTemplate($tpl, array $render) { $registry = new \Drutiny\Registry(); $loader = new \Twig_Loader_Filesystem($registry->templateDirs()); $twig = new \Twig_Environment($loader, array( 'cache' => sys_get_temp_dir() . '/drutiny/cache', 'auto_reload' => TRUE, // 'debug' => true, )); // $twig->addExtension(new \Twig_Extension_Debug()); // Filter to sort arrays by a property. $twig->addFilter(new \Twig_SimpleFilter('psort', function (array $array, array $args = []) { $property = reset($args); usort($array, function ($a, $b) use ($property) { if ($a[$property] == $b[$property]) { return 0; } $index = [$a[$property], $b[$property]]; sort($index); return $index[0] == $a[$property] ? 1 : -1; }); return $array; }, ['is_variadic' => true])); $template = $twig->load($tpl . '.' . $this->getFormat() . '.twig'); $contents = $template->render($render); return $contents; }
php
public function renderTemplate($tpl, array $render) { $registry = new \Drutiny\Registry(); $loader = new \Twig_Loader_Filesystem($registry->templateDirs()); $twig = new \Twig_Environment($loader, array( 'cache' => sys_get_temp_dir() . '/drutiny/cache', 'auto_reload' => TRUE, // 'debug' => true, )); // $twig->addExtension(new \Twig_Extension_Debug()); // Filter to sort arrays by a property. $twig->addFilter(new \Twig_SimpleFilter('psort', function (array $array, array $args = []) { $property = reset($args); usort($array, function ($a, $b) use ($property) { if ($a[$property] == $b[$property]) { return 0; } $index = [$a[$property], $b[$property]]; sort($index); return $index[0] == $a[$property] ? 1 : -1; }); return $array; }, ['is_variadic' => true])); $template = $twig->load($tpl . '.' . $this->getFormat() . '.twig'); $contents = $template->render($render); return $contents; }
[ "public", "function", "renderTemplate", "(", "$", "tpl", ",", "array", "$", "render", ")", "{", "$", "registry", "=", "new", "\\", "Drutiny", "\\", "Registry", "(", ")", ";", "$", "loader", "=", "new", "\\", "Twig_Loader_Filesystem", "(", "$", "registry", "->", "templateDirs", "(", ")", ")", ";", "$", "twig", "=", "new", "\\", "Twig_Environment", "(", "$", "loader", ",", "array", "(", "'cache'", "=>", "sys_get_temp_dir", "(", ")", ".", "'/drutiny/cache'", ",", "'auto_reload'", "=>", "TRUE", ",", "// 'debug' => true,", ")", ")", ";", "// $twig->addExtension(new \\Twig_Extension_Debug());", "// Filter to sort arrays by a property.", "$", "twig", "->", "addFilter", "(", "new", "\\", "Twig_SimpleFilter", "(", "'psort'", ",", "function", "(", "array", "$", "array", ",", "array", "$", "args", "=", "[", "]", ")", "{", "$", "property", "=", "reset", "(", "$", "args", ")", ";", "usort", "(", "$", "array", ",", "function", "(", "$", "a", ",", "$", "b", ")", "use", "(", "$", "property", ")", "{", "if", "(", "$", "a", "[", "$", "property", "]", "==", "$", "b", "[", "$", "property", "]", ")", "{", "return", "0", ";", "}", "$", "index", "=", "[", "$", "a", "[", "$", "property", "]", ",", "$", "b", "[", "$", "property", "]", "]", ";", "sort", "(", "$", "index", ")", ";", "return", "$", "index", "[", "0", "]", "==", "$", "a", "[", "$", "property", "]", "?", "1", ":", "-", "1", ";", "}", ")", ";", "return", "$", "array", ";", "}", ",", "[", "'is_variadic'", "=>", "true", "]", ")", ")", ";", "$", "template", "=", "$", "twig", "->", "load", "(", "$", "tpl", ".", "'.'", ".", "$", "this", "->", "getFormat", "(", ")", ".", "'.twig'", ")", ";", "$", "contents", "=", "$", "template", "->", "render", "(", "$", "render", ")", ";", "return", "$", "contents", ";", "}" ]
Render an HTML template. @param string $tpl The name of the .html.tpl template file to load for rendering. @param array $render An array of variables to be used within the template by the rendering engine. @return string
[ "Render", "an", "HTML", "template", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Report/Format.php#L114-L144
drutiny/drutiny
src/Report/Format.php
Format.setOutput
public function setOutput($filepath = 'stdout') { if ($filepath != 'stdout' && !($filepath instanceof OutputInterface) && !file_exists(dirname($filepath))) { throw new \InvalidArgumentException("Cannot write to $filepath. Parent directory doesn't exist."); } $this->output = $filepath; return $this; }
php
public function setOutput($filepath = 'stdout') { if ($filepath != 'stdout' && !($filepath instanceof OutputInterface) && !file_exists(dirname($filepath))) { throw new \InvalidArgumentException("Cannot write to $filepath. Parent directory doesn't exist."); } $this->output = $filepath; return $this; }
[ "public", "function", "setOutput", "(", "$", "filepath", "=", "'stdout'", ")", "{", "if", "(", "$", "filepath", "!=", "'stdout'", "&&", "!", "(", "$", "filepath", "instanceof", "OutputInterface", ")", "&&", "!", "file_exists", "(", "dirname", "(", "$", "filepath", ")", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Cannot write to $filepath. Parent directory doesn't exist.\"", ")", ";", "}", "$", "this", "->", "output", "=", "$", "filepath", ";", "return", "$", "this", ";", "}" ]
Set the title of the profile.
[ "Set", "the", "title", "of", "the", "profile", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Report/Format.php#L157-L164
drutiny/drutiny
src/AuditResponse/AuditResponse.php
AuditResponse.set
public function set($state = NULL, array $tokens) { switch (TRUE) { case ($state === Audit::SUCCESS): case ($state === Audit::PASS): $state = Audit::SUCCESS; break; case ($state === Audit::FAILURE): case ($state === Audit::FAIL): $state = Audit::FAIL; break; case ($state === Audit::NOT_APPLICABLE): case ($state === NULL): $state = Audit::NOT_APPLICABLE; break; case ($state === Audit::IRRELEVANT): case ($state === Audit::WARNING): case ($state === Audit::WARNING_FAIL): case ($state === Audit::NOTICE): case ($state === Audit::ERROR): // Do nothing. These are all ok. break; default: throw new AuditResponseException("Unknown state set in Audit Response: $state"); } $this->state = $state; $this->tokens = $tokens; }
php
public function set($state = NULL, array $tokens) { switch (TRUE) { case ($state === Audit::SUCCESS): case ($state === Audit::PASS): $state = Audit::SUCCESS; break; case ($state === Audit::FAILURE): case ($state === Audit::FAIL): $state = Audit::FAIL; break; case ($state === Audit::NOT_APPLICABLE): case ($state === NULL): $state = Audit::NOT_APPLICABLE; break; case ($state === Audit::IRRELEVANT): case ($state === Audit::WARNING): case ($state === Audit::WARNING_FAIL): case ($state === Audit::NOTICE): case ($state === Audit::ERROR): // Do nothing. These are all ok. break; default: throw new AuditResponseException("Unknown state set in Audit Response: $state"); } $this->state = $state; $this->tokens = $tokens; }
[ "public", "function", "set", "(", "$", "state", "=", "NULL", ",", "array", "$", "tokens", ")", "{", "switch", "(", "TRUE", ")", "{", "case", "(", "$", "state", "===", "Audit", "::", "SUCCESS", ")", ":", "case", "(", "$", "state", "===", "Audit", "::", "PASS", ")", ":", "$", "state", "=", "Audit", "::", "SUCCESS", ";", "break", ";", "case", "(", "$", "state", "===", "Audit", "::", "FAILURE", ")", ":", "case", "(", "$", "state", "===", "Audit", "::", "FAIL", ")", ":", "$", "state", "=", "Audit", "::", "FAIL", ";", "break", ";", "case", "(", "$", "state", "===", "Audit", "::", "NOT_APPLICABLE", ")", ":", "case", "(", "$", "state", "===", "NULL", ")", ":", "$", "state", "=", "Audit", "::", "NOT_APPLICABLE", ";", "break", ";", "case", "(", "$", "state", "===", "Audit", "::", "IRRELEVANT", ")", ":", "case", "(", "$", "state", "===", "Audit", "::", "WARNING", ")", ":", "case", "(", "$", "state", "===", "Audit", "::", "WARNING_FAIL", ")", ":", "case", "(", "$", "state", "===", "Audit", "::", "NOTICE", ")", ":", "case", "(", "$", "state", "===", "Audit", "::", "ERROR", ")", ":", "// Do nothing. These are all ok.", "break", ";", "default", ":", "throw", "new", "AuditResponseException", "(", "\"Unknown state set in Audit Response: $state\"", ")", ";", "}", "$", "this", "->", "state", "=", "$", "state", ";", "$", "this", "->", "tokens", "=", "$", "tokens", ";", "}" ]
Set the state of the response.
[ "Set", "the", "state", "of", "the", "response", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/AuditResponse/AuditResponse.php#L44-L75
drutiny/drutiny
src/AuditResponse/AuditResponse.php
AuditResponse.getType
public function getType() { if ($this->isNotApplicable()) { return 'not-applicable'; } if ($this->hasError()) { return 'error'; } if ($this->isNotice()) { return 'notice'; } if ($this->hasWarning()) { return 'warning'; } $policy_type = $this->policy->get('type'); if ($policy_type == 'data') { return 'notice'; } return $this->isSuccessful() ? 'success' : 'failure'; }
php
public function getType() { if ($this->isNotApplicable()) { return 'not-applicable'; } if ($this->hasError()) { return 'error'; } if ($this->isNotice()) { return 'notice'; } if ($this->hasWarning()) { return 'warning'; } $policy_type = $this->policy->get('type'); if ($policy_type == 'data') { return 'notice'; } return $this->isSuccessful() ? 'success' : 'failure'; }
[ "public", "function", "getType", "(", ")", "{", "if", "(", "$", "this", "->", "isNotApplicable", "(", ")", ")", "{", "return", "'not-applicable'", ";", "}", "if", "(", "$", "this", "->", "hasError", "(", ")", ")", "{", "return", "'error'", ";", "}", "if", "(", "$", "this", "->", "isNotice", "(", ")", ")", "{", "return", "'notice'", ";", "}", "if", "(", "$", "this", "->", "hasWarning", "(", ")", ")", "{", "return", "'warning'", ";", "}", "$", "policy_type", "=", "$", "this", "->", "policy", "->", "get", "(", "'type'", ")", ";", "if", "(", "$", "policy_type", "==", "'data'", ")", "{", "return", "'notice'", ";", "}", "return", "$", "this", "->", "isSuccessful", "(", ")", "?", "'success'", ":", "'failure'", ";", "}" ]
Get the type of response based on policy type and audit response.
[ "Get", "the", "type", "of", "response", "based", "on", "policy", "type", "and", "audit", "response", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/AuditResponse/AuditResponse.php#L118-L137
drutiny/drutiny
src/AuditResponse/AuditResponse.php
AuditResponse.getSummary
public function getSummary() { $summary = []; switch (TRUE) { case ($this->state === Audit::NOT_APPLICABLE): $summary[] = "This policy is not applicable to this site."; break; case ($this->state === Audit::ERROR): $tokens = [ 'exception' => isset($this->tokens['exception']) ? $this->tokens['exception'] : 'Unknown exception occured.' ]; $summary[] = strtr('Could not determine the state of ' . $this->getTitle() . ' due to an error: ``` exception ```', $tokens); break; case ($this->state === Audit::WARNING): $summary[] = $this->getWarning(); case ($this->state === Audit::SUCCESS): case ($this->state === Audit::PASS): case ($this->state === Audit::NOTICE): $summary[] = $this->getSuccess(); break; case ($this->state === Audit::WARNING_FAIL): $summary[] = $this->getWarning(); case ($this->state === Audit::FAILURE): case ($this->state === Audit::FAIL): $summary[] = $this->getFailure(); break; default: throw new AuditResponseException("Unknown AuditResponse state ({$this->state}). Cannot generate summary for '" . $this->getTitle() . "'."); break; } return implode(PHP_EOL, $summary); }
php
public function getSummary() { $summary = []; switch (TRUE) { case ($this->state === Audit::NOT_APPLICABLE): $summary[] = "This policy is not applicable to this site."; break; case ($this->state === Audit::ERROR): $tokens = [ 'exception' => isset($this->tokens['exception']) ? $this->tokens['exception'] : 'Unknown exception occured.' ]; $summary[] = strtr('Could not determine the state of ' . $this->getTitle() . ' due to an error: ``` exception ```', $tokens); break; case ($this->state === Audit::WARNING): $summary[] = $this->getWarning(); case ($this->state === Audit::SUCCESS): case ($this->state === Audit::PASS): case ($this->state === Audit::NOTICE): $summary[] = $this->getSuccess(); break; case ($this->state === Audit::WARNING_FAIL): $summary[] = $this->getWarning(); case ($this->state === Audit::FAILURE): case ($this->state === Audit::FAIL): $summary[] = $this->getFailure(); break; default: throw new AuditResponseException("Unknown AuditResponse state ({$this->state}). Cannot generate summary for '" . $this->getTitle() . "'."); break; } return implode(PHP_EOL, $summary); }
[ "public", "function", "getSummary", "(", ")", "{", "$", "summary", "=", "[", "]", ";", "switch", "(", "TRUE", ")", "{", "case", "(", "$", "this", "->", "state", "===", "Audit", "::", "NOT_APPLICABLE", ")", ":", "$", "summary", "[", "]", "=", "\"This policy is not applicable to this site.\"", ";", "break", ";", "case", "(", "$", "this", "->", "state", "===", "Audit", "::", "ERROR", ")", ":", "$", "tokens", "=", "[", "'exception'", "=>", "isset", "(", "$", "this", "->", "tokens", "[", "'exception'", "]", ")", "?", "$", "this", "->", "tokens", "[", "'exception'", "]", ":", "'Unknown exception occured.'", "]", ";", "$", "summary", "[", "]", "=", "strtr", "(", "'Could not determine the state of '", ".", "$", "this", "->", "getTitle", "(", ")", ".", "' due to an error:\n```\nexception\n```'", ",", "$", "tokens", ")", ";", "break", ";", "case", "(", "$", "this", "->", "state", "===", "Audit", "::", "WARNING", ")", ":", "$", "summary", "[", "]", "=", "$", "this", "->", "getWarning", "(", ")", ";", "case", "(", "$", "this", "->", "state", "===", "Audit", "::", "SUCCESS", ")", ":", "case", "(", "$", "this", "->", "state", "===", "Audit", "::", "PASS", ")", ":", "case", "(", "$", "this", "->", "state", "===", "Audit", "::", "NOTICE", ")", ":", "$", "summary", "[", "]", "=", "$", "this", "->", "getSuccess", "(", ")", ";", "break", ";", "case", "(", "$", "this", "->", "state", "===", "Audit", "::", "WARNING_FAIL", ")", ":", "$", "summary", "[", "]", "=", "$", "this", "->", "getWarning", "(", ")", ";", "case", "(", "$", "this", "->", "state", "===", "Audit", "::", "FAILURE", ")", ":", "case", "(", "$", "this", "->", "state", "===", "Audit", "::", "FAIL", ")", ":", "$", "summary", "[", "]", "=", "$", "this", "->", "getFailure", "(", ")", ";", "break", ";", "default", ":", "throw", "new", "AuditResponseException", "(", "\"Unknown AuditResponse state ({$this->state}). Cannot generate summary for '\"", ".", "$", "this", "->", "getTitle", "(", ")", ".", "\"'.\"", ")", ";", "break", ";", "}", "return", "implode", "(", "PHP_EOL", ",", "$", "summary", ")", ";", "}" ]
Get the response based on the state outcome. @return string Translated description.
[ "Get", "the", "response", "based", "on", "the", "state", "outcome", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/AuditResponse/AuditResponse.php#L239-L276
drutiny/drutiny
src/Report/ProfileRunMultisiteHTMLReport.php
ProfileRunMultisiteHTMLReport.renderTemplate
public function renderTemplate($tpl, array $render_vars) { $registry = new Registry(); $loader = new \Twig_Loader_Filesystem($registry->templateDirs()); $twig = new \Twig_Environment($loader, array( 'cache' => sys_get_temp_dir() . '/drutiny/cache', 'auto_reload' => TRUE, )); // $filter = new \Twig_SimpleFilter('filterXssAdmin', [$this, 'filterXssAdmin'], [ // 'is_safe' => ['html'], // ]); // $twig->addFilter($filter); $template = $twig->load($tpl . '.html.twig'); $contents = $template->render($render_vars); return $contents; }
php
public function renderTemplate($tpl, array $render_vars) { $registry = new Registry(); $loader = new \Twig_Loader_Filesystem($registry->templateDirs()); $twig = new \Twig_Environment($loader, array( 'cache' => sys_get_temp_dir() . '/drutiny/cache', 'auto_reload' => TRUE, )); // $filter = new \Twig_SimpleFilter('filterXssAdmin', [$this, 'filterXssAdmin'], [ // 'is_safe' => ['html'], // ]); // $twig->addFilter($filter); $template = $twig->load($tpl . '.html.twig'); $contents = $template->render($render_vars); return $contents; }
[ "public", "function", "renderTemplate", "(", "$", "tpl", ",", "array", "$", "render_vars", ")", "{", "$", "registry", "=", "new", "Registry", "(", ")", ";", "$", "loader", "=", "new", "\\", "Twig_Loader_Filesystem", "(", "$", "registry", "->", "templateDirs", "(", ")", ")", ";", "$", "twig", "=", "new", "\\", "Twig_Environment", "(", "$", "loader", ",", "array", "(", "'cache'", "=>", "sys_get_temp_dir", "(", ")", ".", "'/drutiny/cache'", ",", "'auto_reload'", "=>", "TRUE", ",", ")", ")", ";", "// $filter = new \\Twig_SimpleFilter('filterXssAdmin', [$this, 'filterXssAdmin'], [", "// 'is_safe' => ['html'],", "// ]);", "// $twig->addFilter($filter);", "$", "template", "=", "$", "twig", "->", "load", "(", "$", "tpl", ".", "'.html.twig'", ")", ";", "$", "contents", "=", "$", "template", "->", "render", "(", "$", "render_vars", ")", ";", "return", "$", "contents", ";", "}" ]
Render an HTML template. @param string $tpl The name of the .html.tpl template file to load for rendering. @param array $render_vars An array of variables to be used within the template by the rendering engine. @return string
[ "Render", "an", "HTML", "template", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Report/ProfileRunMultisiteHTMLReport.php#L96-L110
drutiny/drutiny
src/Policy/ParameterizedContentTrait.php
ParameterizedContentTrait.getParameterDefaults
public function getParameterDefaults() { $defaults = []; foreach ($this->parameters as $name => $info) { $defaults[$name] = isset($info['default']) ? $info['default'] : null; } return $defaults; }
php
public function getParameterDefaults() { $defaults = []; foreach ($this->parameters as $name => $info) { $defaults[$name] = isset($info['default']) ? $info['default'] : null; } return $defaults; }
[ "public", "function", "getParameterDefaults", "(", ")", "{", "$", "defaults", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "parameters", "as", "$", "name", "=>", "$", "info", ")", "{", "$", "defaults", "[", "$", "name", "]", "=", "isset", "(", "$", "info", "[", "'default'", "]", ")", "?", "$", "info", "[", "'default'", "]", ":", "null", ";", "}", "return", "$", "defaults", ";", "}" ]
Pull default values from each parameter.
[ "Pull", "default", "values", "from", "each", "parameter", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Policy/ParameterizedContentTrait.php#L29-L36
drutiny/drutiny
src/Profile/PolicyDefinition.php
PolicyDefinition.createFromProfile
public static function createFromProfile($name, $weight = 0, $definition = []) { $policyDefinition = new static(); $policyDefinition->setName($name) ->setWeight($weight); if (isset($definition['parameters'])) { $policyDefinition->setParameters($definition['parameters']); } // Load a policy to get defaults. $policy = Policy::load($name); if (isset($definition['severity'])) { $policyDefinition->setSeverity($definition['severity']); } else { $policyDefinition->setSeverity($policy->getSeverity()); } // Track policies that are depended on. // foreach ((array) $policy->get('depends') as $name) { // $policyDefinition->setDependencyPolicyName($name); // } return $policyDefinition; }
php
public static function createFromProfile($name, $weight = 0, $definition = []) { $policyDefinition = new static(); $policyDefinition->setName($name) ->setWeight($weight); if (isset($definition['parameters'])) { $policyDefinition->setParameters($definition['parameters']); } // Load a policy to get defaults. $policy = Policy::load($name); if (isset($definition['severity'])) { $policyDefinition->setSeverity($definition['severity']); } else { $policyDefinition->setSeverity($policy->getSeverity()); } // Track policies that are depended on. // foreach ((array) $policy->get('depends') as $name) { // $policyDefinition->setDependencyPolicyName($name); // } return $policyDefinition; }
[ "public", "static", "function", "createFromProfile", "(", "$", "name", ",", "$", "weight", "=", "0", ",", "$", "definition", "=", "[", "]", ")", "{", "$", "policyDefinition", "=", "new", "static", "(", ")", ";", "$", "policyDefinition", "->", "setName", "(", "$", "name", ")", "->", "setWeight", "(", "$", "weight", ")", ";", "if", "(", "isset", "(", "$", "definition", "[", "'parameters'", "]", ")", ")", "{", "$", "policyDefinition", "->", "setParameters", "(", "$", "definition", "[", "'parameters'", "]", ")", ";", "}", "// Load a policy to get defaults.", "$", "policy", "=", "Policy", "::", "load", "(", "$", "name", ")", ";", "if", "(", "isset", "(", "$", "definition", "[", "'severity'", "]", ")", ")", "{", "$", "policyDefinition", "->", "setSeverity", "(", "$", "definition", "[", "'severity'", "]", ")", ";", "}", "else", "{", "$", "policyDefinition", "->", "setSeverity", "(", "$", "policy", "->", "getSeverity", "(", ")", ")", ";", "}", "// Track policies that are depended on.", "// foreach ((array) $policy->get('depends') as $name) {", "// $policyDefinition->setDependencyPolicyName($name);", "// }", "return", "$", "policyDefinition", ";", "}" ]
Build a PolicyDefinition from Profile input. @var $name string @var $definition array
[ "Build", "a", "PolicyDefinition", "from", "Profile", "input", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Profile/PolicyDefinition.php#L44-L70
drutiny/drutiny
src/Profile/PolicyDefinition.php
PolicyDefinition.getPolicy
public function getPolicy() { $policy = Policy::load($this->getName()); if ($this->getSeverity() !== NULL) { $policy->setSeverity($this->getSeverity()); } foreach ($this->parameters as $param => $value) { $info = ['default' => $value]; $policy->addParameter($param, $info); } return $policy; }
php
public function getPolicy() { $policy = Policy::load($this->getName()); if ($this->getSeverity() !== NULL) { $policy->setSeverity($this->getSeverity()); } foreach ($this->parameters as $param => $value) { $info = ['default' => $value]; $policy->addParameter($param, $info); } return $policy; }
[ "public", "function", "getPolicy", "(", ")", "{", "$", "policy", "=", "Policy", "::", "load", "(", "$", "this", "->", "getName", "(", ")", ")", ";", "if", "(", "$", "this", "->", "getSeverity", "(", ")", "!==", "NULL", ")", "{", "$", "policy", "->", "setSeverity", "(", "$", "this", "->", "getSeverity", "(", ")", ")", ";", "}", "foreach", "(", "$", "this", "->", "parameters", "as", "$", "param", "=>", "$", "value", ")", "{", "$", "info", "=", "[", "'default'", "=>", "$", "value", "]", ";", "$", "policy", "->", "addParameter", "(", "$", "param", ",", "$", "info", ")", ";", "}", "return", "$", "policy", ";", "}" ]
Get the policy for the profile.
[ "Get", "the", "policy", "for", "the", "profile", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Profile/PolicyDefinition.php#L114-L126
drutiny/drutiny
src/Profile/PolicyDefinition.php
PolicyDefinition.setDependencyPolicyName
public function setDependencyPolicyName($name) { $this->positionBefore[$name] = self::createFromProfile($name, $this->getWeight()); return $this; }
php
public function setDependencyPolicyName($name) { $this->positionBefore[$name] = self::createFromProfile($name, $this->getWeight()); return $this; }
[ "public", "function", "setDependencyPolicyName", "(", "$", "name", ")", "{", "$", "this", "->", "positionBefore", "[", "$", "name", "]", "=", "self", "::", "createFromProfile", "(", "$", "name", ",", "$", "this", "->", "getWeight", "(", ")", ")", ";", "return", "$", "this", ";", "}" ]
Track a policy dependency as a policy definition.
[ "Track", "a", "policy", "dependency", "as", "a", "policy", "definition", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Profile/PolicyDefinition.php#L131-L135
drutiny/drutiny
src/Driver/DrushRouter.php
DrushRouter.createFromTarget
public static function createFromTarget(TargetInterface $target, $options = []) { try { $info = $target->getOptions(); $launchers = ['drush-launcher', 'drush.launcher', 'drush']; $binary = 'which ' . implode(' || which ', $launchers); $info = trim($target->exec('$(' . $binary . ') -r ' . $info['root'] . ' status --format=json')); $info = \Drutiny\Utility::jsonDecodeDirty($info, TRUE); // Hack for Acquia Cloud to force use drush9 if drush version reported is v9. if (Comparator::greaterThanOrEqualTo($info['drush-version'], '9.0.0')) { array_unshift($launchers, 'drush9'); $binary = 'which ' . implode(' || which ', $launchers); } $binary = trim($target->exec($binary)); $info = trim($target->exec($binary . ' -r ' . $info['root'] . ' status --format=json')); $info = json_decode($info, TRUE); } catch (ProcessFailedException $e) { Container::getLogger()->error($e->getProcess()->getOutput()); throw $e; } switch (TRUE) { case Comparator::greaterThanOrEqualTo($info['drush-version'], '9.0.0'): $driver = Drush9Driver::createFromTarget($target, $binary); break; default: $driver = DrushDriver::createFromTarget($target, $binary); } $driver->setOptions($options); return $driver; }
php
public static function createFromTarget(TargetInterface $target, $options = []) { try { $info = $target->getOptions(); $launchers = ['drush-launcher', 'drush.launcher', 'drush']; $binary = 'which ' . implode(' || which ', $launchers); $info = trim($target->exec('$(' . $binary . ') -r ' . $info['root'] . ' status --format=json')); $info = \Drutiny\Utility::jsonDecodeDirty($info, TRUE); // Hack for Acquia Cloud to force use drush9 if drush version reported is v9. if (Comparator::greaterThanOrEqualTo($info['drush-version'], '9.0.0')) { array_unshift($launchers, 'drush9'); $binary = 'which ' . implode(' || which ', $launchers); } $binary = trim($target->exec($binary)); $info = trim($target->exec($binary . ' -r ' . $info['root'] . ' status --format=json')); $info = json_decode($info, TRUE); } catch (ProcessFailedException $e) { Container::getLogger()->error($e->getProcess()->getOutput()); throw $e; } switch (TRUE) { case Comparator::greaterThanOrEqualTo($info['drush-version'], '9.0.0'): $driver = Drush9Driver::createFromTarget($target, $binary); break; default: $driver = DrushDriver::createFromTarget($target, $binary); } $driver->setOptions($options); return $driver; }
[ "public", "static", "function", "createFromTarget", "(", "TargetInterface", "$", "target", ",", "$", "options", "=", "[", "]", ")", "{", "try", "{", "$", "info", "=", "$", "target", "->", "getOptions", "(", ")", ";", "$", "launchers", "=", "[", "'drush-launcher'", ",", "'drush.launcher'", ",", "'drush'", "]", ";", "$", "binary", "=", "'which '", ".", "implode", "(", "' || which '", ",", "$", "launchers", ")", ";", "$", "info", "=", "trim", "(", "$", "target", "->", "exec", "(", "'$('", ".", "$", "binary", ".", "') -r '", ".", "$", "info", "[", "'root'", "]", ".", "' status --format=json'", ")", ")", ";", "$", "info", "=", "\\", "Drutiny", "\\", "Utility", "::", "jsonDecodeDirty", "(", "$", "info", ",", "TRUE", ")", ";", "// Hack for Acquia Cloud to force use drush9 if drush version reported is v9.", "if", "(", "Comparator", "::", "greaterThanOrEqualTo", "(", "$", "info", "[", "'drush-version'", "]", ",", "'9.0.0'", ")", ")", "{", "array_unshift", "(", "$", "launchers", ",", "'drush9'", ")", ";", "$", "binary", "=", "'which '", ".", "implode", "(", "' || which '", ",", "$", "launchers", ")", ";", "}", "$", "binary", "=", "trim", "(", "$", "target", "->", "exec", "(", "$", "binary", ")", ")", ";", "$", "info", "=", "trim", "(", "$", "target", "->", "exec", "(", "$", "binary", ".", "' -r '", ".", "$", "info", "[", "'root'", "]", ".", "' status --format=json'", ")", ")", ";", "$", "info", "=", "json_decode", "(", "$", "info", ",", "TRUE", ")", ";", "}", "catch", "(", "ProcessFailedException", "$", "e", ")", "{", "Container", "::", "getLogger", "(", ")", "->", "error", "(", "$", "e", "->", "getProcess", "(", ")", "->", "getOutput", "(", ")", ")", ";", "throw", "$", "e", ";", "}", "switch", "(", "TRUE", ")", "{", "case", "Comparator", "::", "greaterThanOrEqualTo", "(", "$", "info", "[", "'drush-version'", "]", ",", "'9.0.0'", ")", ":", "$", "driver", "=", "Drush9Driver", "::", "createFromTarget", "(", "$", "target", ",", "$", "binary", ")", ";", "break", ";", "default", ":", "$", "driver", "=", "DrushDriver", "::", "createFromTarget", "(", "$", "target", ",", "$", "binary", ")", ";", "}", "$", "driver", "->", "setOptions", "(", "$", "options", ")", ";", "return", "$", "driver", ";", "}" ]
Derive a drush driver from a given Target.
[ "Derive", "a", "drush", "driver", "from", "a", "given", "Target", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Driver/DrushRouter.php#L31-L66
drutiny/drutiny
src/Profile/ProfileSourceDrutinyGitHubIO.php
ProfileSourceDrutinyGitHubIO.getList
public function getList() { $api = new Api(); $list = []; foreach ($api->getProfileList() as $listedPolicy) { $list[$listedPolicy['name']] = $listedPolicy; } return $list; }
php
public function getList() { $api = new Api(); $list = []; foreach ($api->getProfileList() as $listedPolicy) { $list[$listedPolicy['name']] = $listedPolicy; } return $list; }
[ "public", "function", "getList", "(", ")", "{", "$", "api", "=", "new", "Api", "(", ")", ";", "$", "list", "=", "[", "]", ";", "foreach", "(", "$", "api", "->", "getProfileList", "(", ")", "as", "$", "listedPolicy", ")", "{", "$", "list", "[", "$", "listedPolicy", "[", "'name'", "]", "]", "=", "$", "listedPolicy", ";", "}", "return", "$", "list", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Profile/ProfileSourceDrutinyGitHubIO.php#L22-L30
drutiny/drutiny
src/Profile/ProfileSourceDrutinyGitHubIO.php
ProfileSourceDrutinyGitHubIO.load
public function load(array $definition) { $endpoint = str_replace('{baseUri}/api/', '', $definition['_links']['self']['href']); $info = json_decode(Api::getClient()->get($endpoint)->getBody(), TRUE); $info['filepath'] = Api::BaseUrl . $endpoint; $profile = new Profile(); $profile->setTitle($info['title']) ->setName($info['name']) ->setFilepath($info['filepath']); if (isset($info['description'])) { $profile->setDescription($info['description']); } if (isset($info['policies'])) { $v21_keys = ['parameters', 'severity']; foreach ($info['policies'] as $name => $metadata) { // Check for v2.0.x style profiles. if (!empty($metadata) && !count(array_intersect($v21_keys, array_keys($metadata)))) { throw new \Exception("{$info['title']} is a v2.0.x profile. Please upgrade $filepath to v2.2.x schema."); } $weight = array_search($name, array_keys($info['policies'])); $profile->addPolicyDefinition(PolicyDefinition::createFromProfile($name, $weight, $metadata)); } } if (isset($info['excluded_policies']) && is_array($info['excluded_policies'])) { $profile->addExcludedPolicies($info['excluded_policies']); } if (isset($info['include'])) { foreach ($info['include'] as $name) { $include = ProfileSource::loadProfileByName($name); $profile->addInclude($include); } } if (isset($info['format'])) { foreach ($info['format'] as $format => $options) { $profile->addFormatOptions(Format::create($format, $options)); } } return $profile; }
php
public function load(array $definition) { $endpoint = str_replace('{baseUri}/api/', '', $definition['_links']['self']['href']); $info = json_decode(Api::getClient()->get($endpoint)->getBody(), TRUE); $info['filepath'] = Api::BaseUrl . $endpoint; $profile = new Profile(); $profile->setTitle($info['title']) ->setName($info['name']) ->setFilepath($info['filepath']); if (isset($info['description'])) { $profile->setDescription($info['description']); } if (isset($info['policies'])) { $v21_keys = ['parameters', 'severity']; foreach ($info['policies'] as $name => $metadata) { // Check for v2.0.x style profiles. if (!empty($metadata) && !count(array_intersect($v21_keys, array_keys($metadata)))) { throw new \Exception("{$info['title']} is a v2.0.x profile. Please upgrade $filepath to v2.2.x schema."); } $weight = array_search($name, array_keys($info['policies'])); $profile->addPolicyDefinition(PolicyDefinition::createFromProfile($name, $weight, $metadata)); } } if (isset($info['excluded_policies']) && is_array($info['excluded_policies'])) { $profile->addExcludedPolicies($info['excluded_policies']); } if (isset($info['include'])) { foreach ($info['include'] as $name) { $include = ProfileSource::loadProfileByName($name); $profile->addInclude($include); } } if (isset($info['format'])) { foreach ($info['format'] as $format => $options) { $profile->addFormatOptions(Format::create($format, $options)); } } return $profile; }
[ "public", "function", "load", "(", "array", "$", "definition", ")", "{", "$", "endpoint", "=", "str_replace", "(", "'{baseUri}/api/'", ",", "''", ",", "$", "definition", "[", "'_links'", "]", "[", "'self'", "]", "[", "'href'", "]", ")", ";", "$", "info", "=", "json_decode", "(", "Api", "::", "getClient", "(", ")", "->", "get", "(", "$", "endpoint", ")", "->", "getBody", "(", ")", ",", "TRUE", ")", ";", "$", "info", "[", "'filepath'", "]", "=", "Api", "::", "BaseUrl", ".", "$", "endpoint", ";", "$", "profile", "=", "new", "Profile", "(", ")", ";", "$", "profile", "->", "setTitle", "(", "$", "info", "[", "'title'", "]", ")", "->", "setName", "(", "$", "info", "[", "'name'", "]", ")", "->", "setFilepath", "(", "$", "info", "[", "'filepath'", "]", ")", ";", "if", "(", "isset", "(", "$", "info", "[", "'description'", "]", ")", ")", "{", "$", "profile", "->", "setDescription", "(", "$", "info", "[", "'description'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "info", "[", "'policies'", "]", ")", ")", "{", "$", "v21_keys", "=", "[", "'parameters'", ",", "'severity'", "]", ";", "foreach", "(", "$", "info", "[", "'policies'", "]", "as", "$", "name", "=>", "$", "metadata", ")", "{", "// Check for v2.0.x style profiles.", "if", "(", "!", "empty", "(", "$", "metadata", ")", "&&", "!", "count", "(", "array_intersect", "(", "$", "v21_keys", ",", "array_keys", "(", "$", "metadata", ")", ")", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"{$info['title']} is a v2.0.x profile. Please upgrade $filepath to v2.2.x schema.\"", ")", ";", "}", "$", "weight", "=", "array_search", "(", "$", "name", ",", "array_keys", "(", "$", "info", "[", "'policies'", "]", ")", ")", ";", "$", "profile", "->", "addPolicyDefinition", "(", "PolicyDefinition", "::", "createFromProfile", "(", "$", "name", ",", "$", "weight", ",", "$", "metadata", ")", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "info", "[", "'excluded_policies'", "]", ")", "&&", "is_array", "(", "$", "info", "[", "'excluded_policies'", "]", ")", ")", "{", "$", "profile", "->", "addExcludedPolicies", "(", "$", "info", "[", "'excluded_policies'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "info", "[", "'include'", "]", ")", ")", "{", "foreach", "(", "$", "info", "[", "'include'", "]", "as", "$", "name", ")", "{", "$", "include", "=", "ProfileSource", "::", "loadProfileByName", "(", "$", "name", ")", ";", "$", "profile", "->", "addInclude", "(", "$", "include", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "info", "[", "'format'", "]", ")", ")", "{", "foreach", "(", "$", "info", "[", "'format'", "]", "as", "$", "format", "=>", "$", "options", ")", "{", "$", "profile", "->", "addFormatOptions", "(", "Format", "::", "create", "(", "$", "format", ",", "$", "options", ")", ")", ";", "}", "}", "return", "$", "profile", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Profile/ProfileSourceDrutinyGitHubIO.php#L35-L79
drutiny/drutiny
src/Target/Target.php
Target.parseTarget
static public function parseTarget($target) { $target_name = 'drush'; $target_data = $target; if (strpos($target, ':') !== FALSE) { list($target_name, $target_data) = explode(':', $target, 2); } return [$target_name, $target_data]; }
php
static public function parseTarget($target) { $target_name = 'drush'; $target_data = $target; if (strpos($target, ':') !== FALSE) { list($target_name, $target_data) = explode(':', $target, 2); } return [$target_name, $target_data]; }
[ "static", "public", "function", "parseTarget", "(", "$", "target", ")", "{", "$", "target_name", "=", "'drush'", ";", "$", "target_data", "=", "$", "target", ";", "if", "(", "strpos", "(", "$", "target", ",", "':'", ")", "!==", "FALSE", ")", "{", "list", "(", "$", "target_name", ",", "$", "target_data", ")", "=", "explode", "(", "':'", ",", "$", "target", ",", "2", ")", ";", "}", "return", "[", "$", "target_name", ",", "$", "target_data", "]", ";", "}" ]
Parse a target argument into the target driver and data.
[ "Parse", "a", "target", "argument", "into", "the", "target", "driver", "and", "data", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Target/Target.php#L66-L74
drutiny/drutiny
src/Target/Target.php
Target.getMetadata
final public function getMetadata() { $item = Container::cache('target')->getItem('metadata'); if (!$item->isHit()) { $metadata = []; $reflection = new \ReflectionClass($this); $interfaces = $reflection->getInterfaces(); $reader = new AnnotationReader(); foreach ($interfaces as $interface) { $methods = $interface->getMethods(\ReflectionMethod::IS_PUBLIC); foreach ($methods as $method) { $annotation = $reader->getMethodAnnotation($method, 'Drutiny\Annotation\Metadata'); if (empty($annotation)) { continue; } $metadata[$annotation->name] = $method->name; } } Container::cache('target')->save($item->set($metadata)); } return $item->get(); }
php
final public function getMetadata() { $item = Container::cache('target')->getItem('metadata'); if (!$item->isHit()) { $metadata = []; $reflection = new \ReflectionClass($this); $interfaces = $reflection->getInterfaces(); $reader = new AnnotationReader(); foreach ($interfaces as $interface) { $methods = $interface->getMethods(\ReflectionMethod::IS_PUBLIC); foreach ($methods as $method) { $annotation = $reader->getMethodAnnotation($method, 'Drutiny\Annotation\Metadata'); if (empty($annotation)) { continue; } $metadata[$annotation->name] = $method->name; } } Container::cache('target')->save($item->set($metadata)); } return $item->get(); }
[ "final", "public", "function", "getMetadata", "(", ")", "{", "$", "item", "=", "Container", "::", "cache", "(", "'target'", ")", "->", "getItem", "(", "'metadata'", ")", ";", "if", "(", "!", "$", "item", "->", "isHit", "(", ")", ")", "{", "$", "metadata", "=", "[", "]", ";", "$", "reflection", "=", "new", "\\", "ReflectionClass", "(", "$", "this", ")", ";", "$", "interfaces", "=", "$", "reflection", "->", "getInterfaces", "(", ")", ";", "$", "reader", "=", "new", "AnnotationReader", "(", ")", ";", "foreach", "(", "$", "interfaces", "as", "$", "interface", ")", "{", "$", "methods", "=", "$", "interface", "->", "getMethods", "(", "\\", "ReflectionMethod", "::", "IS_PUBLIC", ")", ";", "foreach", "(", "$", "methods", "as", "$", "method", ")", "{", "$", "annotation", "=", "$", "reader", "->", "getMethodAnnotation", "(", "$", "method", ",", "'Drutiny\\Annotation\\Metadata'", ")", ";", "if", "(", "empty", "(", "$", "annotation", ")", ")", "{", "continue", ";", "}", "$", "metadata", "[", "$", "annotation", "->", "name", "]", "=", "$", "method", "->", "name", ";", "}", "}", "Container", "::", "cache", "(", "'target'", ")", "->", "save", "(", "$", "item", "->", "set", "(", "$", "metadata", ")", ")", ";", "}", "return", "$", "item", "->", "get", "(", ")", ";", "}" ]
Pull metadata from Drutiny\Target\Metadata interfaces. @return array of metatdata keyed by metadata name.
[ "Pull", "metadata", "from", "Drutiny", "\\", "Target", "\\", "Metadata", "interfaces", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Target/Target.php#L89-L112
drutiny/drutiny
src/Target/DrushTarget.php
DrushTarget.runDrushCommand
public function runDrushCommand($method, array $args, array $options, $pipe = '', $bin = 'drush') { $parameters = [ '@method' => $method, '@args' => implode(' ', $args), '@options' => implode(' ', $options), '@alias' => $this->getAlias(), '@pipe' => $pipe, '@drush' => $bin, ]; // Do not use a locally sourced alias if the command will be executed remotely. if (isset($this->options['remote-host'])) { $parameters['@root'] = $this->options['root']; return $this->exec('@pipe @drush -r @root @options @method @args', $parameters); } return $this->exec('@pipe @drush @alias @options @method @args', $parameters); }
php
public function runDrushCommand($method, array $args, array $options, $pipe = '', $bin = 'drush') { $parameters = [ '@method' => $method, '@args' => implode(' ', $args), '@options' => implode(' ', $options), '@alias' => $this->getAlias(), '@pipe' => $pipe, '@drush' => $bin, ]; // Do not use a locally sourced alias if the command will be executed remotely. if (isset($this->options['remote-host'])) { $parameters['@root'] = $this->options['root']; return $this->exec('@pipe @drush -r @root @options @method @args', $parameters); } return $this->exec('@pipe @drush @alias @options @method @args', $parameters); }
[ "public", "function", "runDrushCommand", "(", "$", "method", ",", "array", "$", "args", ",", "array", "$", "options", ",", "$", "pipe", "=", "''", ",", "$", "bin", "=", "'drush'", ")", "{", "$", "parameters", "=", "[", "'@method'", "=>", "$", "method", ",", "'@args'", "=>", "implode", "(", "' '", ",", "$", "args", ")", ",", "'@options'", "=>", "implode", "(", "' '", ",", "$", "options", ")", ",", "'@alias'", "=>", "$", "this", "->", "getAlias", "(", ")", ",", "'@pipe'", "=>", "$", "pipe", ",", "'@drush'", "=>", "$", "bin", ",", "]", ";", "// Do not use a locally sourced alias if the command will be executed remotely.", "if", "(", "isset", "(", "$", "this", "->", "options", "[", "'remote-host'", "]", ")", ")", "{", "$", "parameters", "[", "'@root'", "]", "=", "$", "this", "->", "options", "[", "'root'", "]", ";", "return", "$", "this", "->", "exec", "(", "'@pipe @drush -r @root @options @method @args'", ",", "$", "parameters", ")", ";", "}", "return", "$", "this", "->", "exec", "(", "'@pipe @drush @alias @options @method @args'", ",", "$", "parameters", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Target/DrushTarget.php#L60-L76
drutiny/drutiny
src/PolicySource/PolicySource.php
PolicySource.loadPolicyByName
public static function loadPolicyByName($name) { $list = self::getPolicyList(); if (!isset($list[$name])) { $list = self::getPolicyList(TRUE); if (!isset($list[$name])) { throw new UnknownPolicyException("$name does not exist."); } throw new UnavailablePolicyException("$name requires {$list[$name]['class']} but is not available in this environment."); } $definition = $list[$name]; try { return self::getSource($definition['source'])->load($definition); } catch (\InvalidArgumentException $e) { Container::getLogger()->warning($e->getMessage()); throw new UnavailablePolicyException("$name requires {$list[$name]['class']} but is not available in this environment."); } }
php
public static function loadPolicyByName($name) { $list = self::getPolicyList(); if (!isset($list[$name])) { $list = self::getPolicyList(TRUE); if (!isset($list[$name])) { throw new UnknownPolicyException("$name does not exist."); } throw new UnavailablePolicyException("$name requires {$list[$name]['class']} but is not available in this environment."); } $definition = $list[$name]; try { return self::getSource($definition['source'])->load($definition); } catch (\InvalidArgumentException $e) { Container::getLogger()->warning($e->getMessage()); throw new UnavailablePolicyException("$name requires {$list[$name]['class']} but is not available in this environment."); } }
[ "public", "static", "function", "loadPolicyByName", "(", "$", "name", ")", "{", "$", "list", "=", "self", "::", "getPolicyList", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "list", "[", "$", "name", "]", ")", ")", "{", "$", "list", "=", "self", "::", "getPolicyList", "(", "TRUE", ")", ";", "if", "(", "!", "isset", "(", "$", "list", "[", "$", "name", "]", ")", ")", "{", "throw", "new", "UnknownPolicyException", "(", "\"$name does not exist.\"", ")", ";", "}", "throw", "new", "UnavailablePolicyException", "(", "\"$name requires {$list[$name]['class']} but is not available in this environment.\"", ")", ";", "}", "$", "definition", "=", "$", "list", "[", "$", "name", "]", ";", "try", "{", "return", "self", "::", "getSource", "(", "$", "definition", "[", "'source'", "]", ")", "->", "load", "(", "$", "definition", ")", ";", "}", "catch", "(", "\\", "InvalidArgumentException", "$", "e", ")", "{", "Container", "::", "getLogger", "(", ")", "->", "warning", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "throw", "new", "UnavailablePolicyException", "(", "\"$name requires {$list[$name]['class']} but is not available in this environment.\"", ")", ";", "}", "}" ]
Load policy by name. @param $name string
[ "Load", "policy", "by", "name", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/PolicySource/PolicySource.php#L15-L35
drutiny/drutiny
src/PolicySource/PolicySource.php
PolicySource.getPolicyList
public static function getPolicyList($include_invalid = FALSE) { static $list, $available_list; if ($include_invalid && !empty($list)) { return $list; } if (!empty($available_list)) { return $available_list; } $timer = Container::utility()->timer()->start(); Container::getLogger()->notice('Loading profile sources'); $lists = []; foreach (self::getSources() as $source) { foreach ($source->getList() as $name => $item) { $item['source'] = $source->getName(); $list[$name] = $item; } } $timer->stop(); Container::getLogger()->info(sprintf("Loaded policy sources in %ss", $timer->getTime())); if ($include_invalid) { return $list; } $available_list = array_filter($list, function ($listedPolicy) { return class_exists($listedPolicy['class']); }); return $available_list; }
php
public static function getPolicyList($include_invalid = FALSE) { static $list, $available_list; if ($include_invalid && !empty($list)) { return $list; } if (!empty($available_list)) { return $available_list; } $timer = Container::utility()->timer()->start(); Container::getLogger()->notice('Loading profile sources'); $lists = []; foreach (self::getSources() as $source) { foreach ($source->getList() as $name => $item) { $item['source'] = $source->getName(); $list[$name] = $item; } } $timer->stop(); Container::getLogger()->info(sprintf("Loaded policy sources in %ss", $timer->getTime())); if ($include_invalid) { return $list; } $available_list = array_filter($list, function ($listedPolicy) { return class_exists($listedPolicy['class']); }); return $available_list; }
[ "public", "static", "function", "getPolicyList", "(", "$", "include_invalid", "=", "FALSE", ")", "{", "static", "$", "list", ",", "$", "available_list", ";", "if", "(", "$", "include_invalid", "&&", "!", "empty", "(", "$", "list", ")", ")", "{", "return", "$", "list", ";", "}", "if", "(", "!", "empty", "(", "$", "available_list", ")", ")", "{", "return", "$", "available_list", ";", "}", "$", "timer", "=", "Container", "::", "utility", "(", ")", "->", "timer", "(", ")", "->", "start", "(", ")", ";", "Container", "::", "getLogger", "(", ")", "->", "notice", "(", "'Loading profile sources'", ")", ";", "$", "lists", "=", "[", "]", ";", "foreach", "(", "self", "::", "getSources", "(", ")", "as", "$", "source", ")", "{", "foreach", "(", "$", "source", "->", "getList", "(", ")", "as", "$", "name", "=>", "$", "item", ")", "{", "$", "item", "[", "'source'", "]", "=", "$", "source", "->", "getName", "(", ")", ";", "$", "list", "[", "$", "name", "]", "=", "$", "item", ";", "}", "}", "$", "timer", "->", "stop", "(", ")", ";", "Container", "::", "getLogger", "(", ")", "->", "info", "(", "sprintf", "(", "\"Loaded policy sources in %ss\"", ",", "$", "timer", "->", "getTime", "(", ")", ")", ")", ";", "if", "(", "$", "include_invalid", ")", "{", "return", "$", "list", ";", "}", "$", "available_list", "=", "array_filter", "(", "$", "list", ",", "function", "(", "$", "listedPolicy", ")", "{", "return", "class_exists", "(", "$", "listedPolicy", "[", "'class'", "]", ")", ";", "}", ")", ";", "return", "$", "available_list", ";", "}" ]
Acquire a list of available policies. @return array of policy information arrays.
[ "Acquire", "a", "list", "of", "available", "policies", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/PolicySource/PolicySource.php#L42-L76
drutiny/drutiny
src/PolicySource/PolicySource.php
PolicySource.loadAll
public static function loadAll() { static $list = []; if (!empty($list)) { return $list; } foreach (self::getPolicyList() as $definition) { try { $list[$definition['name']] = self::loadPolicyByName($definition['name']); } catch (\Exception $e) { Container::getLogger()->warning("[{$definition['name']}] " . $e->getMessage()); } } return $list; }
php
public static function loadAll() { static $list = []; if (!empty($list)) { return $list; } foreach (self::getPolicyList() as $definition) { try { $list[$definition['name']] = self::loadPolicyByName($definition['name']); } catch (\Exception $e) { Container::getLogger()->warning("[{$definition['name']}] " . $e->getMessage()); } } return $list; }
[ "public", "static", "function", "loadAll", "(", ")", "{", "static", "$", "list", "=", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "list", ")", ")", "{", "return", "$", "list", ";", "}", "foreach", "(", "self", "::", "getPolicyList", "(", ")", "as", "$", "definition", ")", "{", "try", "{", "$", "list", "[", "$", "definition", "[", "'name'", "]", "]", "=", "self", "::", "loadPolicyByName", "(", "$", "definition", "[", "'name'", "]", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "Container", "::", "getLogger", "(", ")", "->", "warning", "(", "\"[{$definition['name']}] \"", ".", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "}", "return", "$", "list", ";", "}" ]
Load all policies as loaded Policy objects.
[ "Load", "all", "policies", "as", "loaded", "Policy", "objects", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/PolicySource/PolicySource.php#L81-L96
drutiny/drutiny
src/Utility.php
_UtilityTimer.stop
public function stop() { $this->end = microtime(true); return bcsub($this->end, $this->start, 2); }
php
public function stop() { $this->end = microtime(true); return bcsub($this->end, $this->start, 2); }
[ "public", "function", "stop", "(", ")", "{", "$", "this", "->", "end", "=", "microtime", "(", "true", ")", ";", "return", "bcsub", "(", "$", "this", "->", "end", ",", "$", "this", "->", "start", ",", "2", ")", ";", "}" ]
End the timer. @return int The number of seconds the timer ran for (rounded).
[ "End", "the", "timer", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Utility.php#L52-L56
drutiny/drutiny
src/Policy.php
Policy.getParameterDefaults
public function getParameterDefaults() { $defaults = $this->useTraitgetParameterDefaults(); $audit = (new Registry)->getAuditMedtadata($this->class); // Validation. Look for parameters specificed by the policy and not the // audit. foreach (array_keys($defaults) as $name) { if (!isset($audit->params[$name])) { Container::getLogger()->warning(strtr('Policy :name documents parameter ":param" not documented by :class.', [ ':name' => $this->name, ':param' => $name, ':class' => $this->class, ])); } } foreach ($audit->params as $param) { if (!isset($defaults[$param->name])) { $defaults[$param->name] = isset($param->default) ? $param->default : null; } } $defaults['_chart'] = array_map(function ($chart) { $chart += $chart + [ 'type' => 'bar', 'hide-table' => false, 'stacked' => false, 'series' => [], 'series-labels' => [], 'labels' => [], 'title' => '' ]; $el = []; foreach ($chart as $attr => $value) { $value = is_array($value) ? implode(',', $value) : $value; $el[] = $attr . '="' . $value . '"'; } return '[[[' . implode(' ', $el) . ']]]'; }, $this->chart); return $defaults; }
php
public function getParameterDefaults() { $defaults = $this->useTraitgetParameterDefaults(); $audit = (new Registry)->getAuditMedtadata($this->class); // Validation. Look for parameters specificed by the policy and not the // audit. foreach (array_keys($defaults) as $name) { if (!isset($audit->params[$name])) { Container::getLogger()->warning(strtr('Policy :name documents parameter ":param" not documented by :class.', [ ':name' => $this->name, ':param' => $name, ':class' => $this->class, ])); } } foreach ($audit->params as $param) { if (!isset($defaults[$param->name])) { $defaults[$param->name] = isset($param->default) ? $param->default : null; } } $defaults['_chart'] = array_map(function ($chart) { $chart += $chart + [ 'type' => 'bar', 'hide-table' => false, 'stacked' => false, 'series' => [], 'series-labels' => [], 'labels' => [], 'title' => '' ]; $el = []; foreach ($chart as $attr => $value) { $value = is_array($value) ? implode(',', $value) : $value; $el[] = $attr . '="' . $value . '"'; } return '[[[' . implode(' ', $el) . ']]]'; }, $this->chart); return $defaults; }
[ "public", "function", "getParameterDefaults", "(", ")", "{", "$", "defaults", "=", "$", "this", "->", "useTraitgetParameterDefaults", "(", ")", ";", "$", "audit", "=", "(", "new", "Registry", ")", "->", "getAuditMedtadata", "(", "$", "this", "->", "class", ")", ";", "// Validation. Look for parameters specificed by the policy and not the", "// audit.", "foreach", "(", "array_keys", "(", "$", "defaults", ")", "as", "$", "name", ")", "{", "if", "(", "!", "isset", "(", "$", "audit", "->", "params", "[", "$", "name", "]", ")", ")", "{", "Container", "::", "getLogger", "(", ")", "->", "warning", "(", "strtr", "(", "'Policy :name documents parameter \":param\" not documented by :class.'", ",", "[", "':name'", "=>", "$", "this", "->", "name", ",", "':param'", "=>", "$", "name", ",", "':class'", "=>", "$", "this", "->", "class", ",", "]", ")", ")", ";", "}", "}", "foreach", "(", "$", "audit", "->", "params", "as", "$", "param", ")", "{", "if", "(", "!", "isset", "(", "$", "defaults", "[", "$", "param", "->", "name", "]", ")", ")", "{", "$", "defaults", "[", "$", "param", "->", "name", "]", "=", "isset", "(", "$", "param", "->", "default", ")", "?", "$", "param", "->", "default", ":", "null", ";", "}", "}", "$", "defaults", "[", "'_chart'", "]", "=", "array_map", "(", "function", "(", "$", "chart", ")", "{", "$", "chart", "+=", "$", "chart", "+", "[", "'type'", "=>", "'bar'", ",", "'hide-table'", "=>", "false", ",", "'stacked'", "=>", "false", ",", "'series'", "=>", "[", "]", ",", "'series-labels'", "=>", "[", "]", ",", "'labels'", "=>", "[", "]", ",", "'title'", "=>", "''", "]", ";", "$", "el", "=", "[", "]", ";", "foreach", "(", "$", "chart", "as", "$", "attr", "=>", "$", "value", ")", "{", "$", "value", "=", "is_array", "(", "$", "value", ")", "?", "implode", "(", "','", ",", "$", "value", ")", ":", "$", "value", ";", "$", "el", "[", "]", "=", "$", "attr", ".", "'=\"'", ".", "$", "value", ".", "'\"'", ";", "}", "return", "'[[['", ".", "implode", "(", "' '", ",", "$", "el", ")", ".", "']]]'", ";", "}", ",", "$", "this", "->", "chart", ")", ";", "return", "$", "defaults", ";", "}" ]
Override ParameterizedContentTrait::getParameterDefaults.
[ "Override", "ParameterizedContentTrait", "::", "getParameterDefaults", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Policy.php#L161-L206
drutiny/drutiny
src/PolicySource/LocalFs.php
LocalFs.getList
public function getList() { $cache = Container::cache($this->getName())->getItem('list'); if ($cache->isHit()) { return $cache->get(); } $finder = Config::getFinder()->name('*.policy.yml'); $list = []; foreach ($finder as $file) { $filename = $file->getRelativePathname(); $policy = Yaml::parse(file_get_contents($filename)); $policy['filepath'] = $filename; $list[$policy['name']] = $policy; } Container::cache($this->getName())->save( $cache->set($list)->expiresAfter(3600) ); return $list; }
php
public function getList() { $cache = Container::cache($this->getName())->getItem('list'); if ($cache->isHit()) { return $cache->get(); } $finder = Config::getFinder()->name('*.policy.yml'); $list = []; foreach ($finder as $file) { $filename = $file->getRelativePathname(); $policy = Yaml::parse(file_get_contents($filename)); $policy['filepath'] = $filename; $list[$policy['name']] = $policy; } Container::cache($this->getName())->save( $cache->set($list)->expiresAfter(3600) ); return $list; }
[ "public", "function", "getList", "(", ")", "{", "$", "cache", "=", "Container", "::", "cache", "(", "$", "this", "->", "getName", "(", ")", ")", "->", "getItem", "(", "'list'", ")", ";", "if", "(", "$", "cache", "->", "isHit", "(", ")", ")", "{", "return", "$", "cache", "->", "get", "(", ")", ";", "}", "$", "finder", "=", "Config", "::", "getFinder", "(", ")", "->", "name", "(", "'*.policy.yml'", ")", ";", "$", "list", "=", "[", "]", ";", "foreach", "(", "$", "finder", "as", "$", "file", ")", "{", "$", "filename", "=", "$", "file", "->", "getRelativePathname", "(", ")", ";", "$", "policy", "=", "Yaml", "::", "parse", "(", "file_get_contents", "(", "$", "filename", ")", ")", ";", "$", "policy", "[", "'filepath'", "]", "=", "$", "filename", ";", "$", "list", "[", "$", "policy", "[", "'name'", "]", "]", "=", "$", "policy", ";", "}", "Container", "::", "cache", "(", "$", "this", "->", "getName", "(", ")", ")", "->", "save", "(", "$", "cache", "->", "set", "(", "$", "list", ")", "->", "expiresAfter", "(", "3600", ")", ")", ";", "return", "$", "list", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/PolicySource/LocalFs.php#L25-L44
drutiny/drutiny
src/Driver/DrushDriver.php
DrushDriver.createFromTarget
public static function createFromTarget(TargetInterface $target, $drush_bin = 'drush') { $options = []; $alias = '@self'; if ($target instanceof DrushTargetInterface) { $alias = $target->getAlias(); } return new static($target, $drush_bin, $options, $alias); }
php
public static function createFromTarget(TargetInterface $target, $drush_bin = 'drush') { $options = []; $alias = '@self'; if ($target instanceof DrushTargetInterface) { $alias = $target->getAlias(); } return new static($target, $drush_bin, $options, $alias); }
[ "public", "static", "function", "createFromTarget", "(", "TargetInterface", "$", "target", ",", "$", "drush_bin", "=", "'drush'", ")", "{", "$", "options", "=", "[", "]", ";", "$", "alias", "=", "'@self'", ";", "if", "(", "$", "target", "instanceof", "DrushTargetInterface", ")", "{", "$", "alias", "=", "$", "target", "->", "getAlias", "(", ")", ";", "}", "return", "new", "static", "(", "$", "target", ",", "$", "drush_bin", ",", "$", "options", ",", "$", "alias", ")", ";", "}" ]
Instansiate a new Drush Driver instance. @param TargetInterface $target @param string $drush_bin path to drush executable.
[ "Instansiate", "a", "new", "Drush", "Driver", "instance", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Driver/DrushDriver.php#L52-L60
drutiny/drutiny
src/Driver/DrushDriver.php
DrushDriver.runCommand
protected function runCommand($method, $args, $pipe = '') { // Hand task off to Target directly if it supports it. if ($this->target instanceof DrushExecutableTargetInterface) { return $this->target->runDrushCommand($method, $args, $this->getOptions(), $pipe, $this->drushBin); } return $this->target->exec('@pipe @bin @alias @options @method @args', [ '@method' => $method, '@alias' => $this->getAlias(), '@bin' => $this->drushBin, '@args' => implode(' ', $args), '@options' => implode(' ', $this->getOptions()), '@pipe' => $pipe ]); }
php
protected function runCommand($method, $args, $pipe = '') { // Hand task off to Target directly if it supports it. if ($this->target instanceof DrushExecutableTargetInterface) { return $this->target->runDrushCommand($method, $args, $this->getOptions(), $pipe, $this->drushBin); } return $this->target->exec('@pipe @bin @alias @options @method @args', [ '@method' => $method, '@alias' => $this->getAlias(), '@bin' => $this->drushBin, '@args' => implode(' ', $args), '@options' => implode(' ', $this->getOptions()), '@pipe' => $pipe ]); }
[ "protected", "function", "runCommand", "(", "$", "method", ",", "$", "args", ",", "$", "pipe", "=", "''", ")", "{", "// Hand task off to Target directly if it supports it.", "if", "(", "$", "this", "->", "target", "instanceof", "DrushExecutableTargetInterface", ")", "{", "return", "$", "this", "->", "target", "->", "runDrushCommand", "(", "$", "method", ",", "$", "args", ",", "$", "this", "->", "getOptions", "(", ")", ",", "$", "pipe", ",", "$", "this", "->", "drushBin", ")", ";", "}", "return", "$", "this", "->", "target", "->", "exec", "(", "'@pipe @bin @alias @options @method @args'", ",", "[", "'@method'", "=>", "$", "method", ",", "'@alias'", "=>", "$", "this", "->", "getAlias", "(", ")", ",", "'@bin'", "=>", "$", "this", "->", "drushBin", ",", "'@args'", "=>", "implode", "(", "' '", ",", "$", "args", ")", ",", "'@options'", "=>", "implode", "(", "' '", ",", "$", "this", "->", "getOptions", "(", ")", ")", ",", "'@pipe'", "=>", "$", "pipe", "]", ")", ";", "}" ]
Run the drush command.
[ "Run", "the", "drush", "command", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Driver/DrushDriver.php#L98-L111
drutiny/drutiny
src/Driver/DrushDriver.php
DrushDriver.setOptions
public function setOptions(array $options) { foreach ($options as $key => $value) { if (is_int($key)) { $option = '--' . $value; } elseif (strlen($key) == 1) { $option = '-' . $key; if (!empty($value)) { $option .= ' ' . escapeshellarg($value); } } else { // Do not render --uri=default. if ($key == 'uri' && $value == 'default') { continue; } $option = '--' . $key; if (!empty($value)) { $option .= '=' . escapeshellarg($value); } } if (!in_array($option, $this->options)) { $this->options[] = $option; } } return $this; }
php
public function setOptions(array $options) { foreach ($options as $key => $value) { if (is_int($key)) { $option = '--' . $value; } elseif (strlen($key) == 1) { $option = '-' . $key; if (!empty($value)) { $option .= ' ' . escapeshellarg($value); } } else { // Do not render --uri=default. if ($key == 'uri' && $value == 'default') { continue; } $option = '--' . $key; if (!empty($value)) { $option .= '=' . escapeshellarg($value); } } if (!in_array($option, $this->options)) { $this->options[] = $option; } } return $this; }
[ "public", "function", "setOptions", "(", "array", "$", "options", ")", "{", "foreach", "(", "$", "options", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_int", "(", "$", "key", ")", ")", "{", "$", "option", "=", "'--'", ".", "$", "value", ";", "}", "elseif", "(", "strlen", "(", "$", "key", ")", "==", "1", ")", "{", "$", "option", "=", "'-'", ".", "$", "key", ";", "if", "(", "!", "empty", "(", "$", "value", ")", ")", "{", "$", "option", ".=", "' '", ".", "escapeshellarg", "(", "$", "value", ")", ";", "}", "}", "else", "{", "// Do not render --uri=default.", "if", "(", "$", "key", "==", "'uri'", "&&", "$", "value", "==", "'default'", ")", "{", "continue", ";", "}", "$", "option", "=", "'--'", ".", "$", "key", ";", "if", "(", "!", "empty", "(", "$", "value", ")", ")", "{", "$", "option", ".=", "'='", ".", "escapeshellarg", "(", "$", "value", ")", ";", "}", "}", "if", "(", "!", "in_array", "(", "$", "option", ",", "$", "this", "->", "options", ")", ")", "{", "$", "this", "->", "options", "[", "]", "=", "$", "option", ";", "}", "}", "return", "$", "this", ";", "}" ]
Set drush options.
[ "Set", "drush", "options", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Driver/DrushDriver.php#L129-L155
drutiny/drutiny
src/Driver/DrushDriver.php
DrushDriver.cleanOutput
private function cleanOutput($output) { if (!is_array($output)) { $output = explode(PHP_EOL, $output); } // Datetime weirdness. Apparently this is caused by theming issues on the // remote theme. Why it is being called when executed via CLI is another // story. foreach ($output as $key => $value) { $invalid_strings = [ 'date_timezone_set() expects parameter', 'date_format() expects parameter', 'common.inc:20', 'given common.inc:20', 'Warning: Using a password on the command line interface can be insecure.', ]; foreach ($invalid_strings as $invalid_string) { if (strpos($value, $invalid_string) === 0) { unset($output[$key]); } } } // Remove blank lines. $output = array_filter($output); // Ensure we are returning arrays with no key association. return array_values($output); }
php
private function cleanOutput($output) { if (!is_array($output)) { $output = explode(PHP_EOL, $output); } // Datetime weirdness. Apparently this is caused by theming issues on the // remote theme. Why it is being called when executed via CLI is another // story. foreach ($output as $key => $value) { $invalid_strings = [ 'date_timezone_set() expects parameter', 'date_format() expects parameter', 'common.inc:20', 'given common.inc:20', 'Warning: Using a password on the command line interface can be insecure.', ]; foreach ($invalid_strings as $invalid_string) { if (strpos($value, $invalid_string) === 0) { unset($output[$key]); } } } // Remove blank lines. $output = array_filter($output); // Ensure we are returning arrays with no key association. return array_values($output); }
[ "private", "function", "cleanOutput", "(", "$", "output", ")", "{", "if", "(", "!", "is_array", "(", "$", "output", ")", ")", "{", "$", "output", "=", "explode", "(", "PHP_EOL", ",", "$", "output", ")", ";", "}", "// Datetime weirdness. Apparently this is caused by theming issues on the", "// remote theme. Why it is being called when executed via CLI is another", "// story.", "foreach", "(", "$", "output", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "invalid_strings", "=", "[", "'date_timezone_set() expects parameter'", ",", "'date_format() expects parameter'", ",", "'common.inc:20'", ",", "'given common.inc:20'", ",", "'Warning: Using a password on the command line interface can be insecure.'", ",", "]", ";", "foreach", "(", "$", "invalid_strings", "as", "$", "invalid_string", ")", "{", "if", "(", "strpos", "(", "$", "value", ",", "$", "invalid_string", ")", "===", "0", ")", "{", "unset", "(", "$", "output", "[", "$", "key", "]", ")", ";", "}", "}", "}", "// Remove blank lines.", "$", "output", "=", "array_filter", "(", "$", "output", ")", ";", "// Ensure we are returning arrays with no key association.", "return", "array_values", "(", "$", "output", ")", ";", "}" ]
Clean up the output of Drush. @param $output @return array
[ "Clean", "up", "the", "output", "of", "Drush", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Driver/DrushDriver.php#L163-L191
drutiny/drutiny
src/Driver/DrushDriver.php
DrushDriver.moduleEnabled
public function moduleEnabled($name) { $this->options[] = '--format=json'; $modules = $this->__call('pmList', []); if (!$modules = json_decode($modules, TRUE)) { throw new DrushFormatException("Cannot parse json output from drush: $modules", $modules); } $this->options = []; return isset($modules[$name]) && $modules[$name]['status'] === 'Enabled'; }
php
public function moduleEnabled($name) { $this->options[] = '--format=json'; $modules = $this->__call('pmList', []); if (!$modules = json_decode($modules, TRUE)) { throw new DrushFormatException("Cannot parse json output from drush: $modules", $modules); } $this->options = []; return isset($modules[$name]) && $modules[$name]['status'] === 'Enabled'; }
[ "public", "function", "moduleEnabled", "(", "$", "name", ")", "{", "$", "this", "->", "options", "[", "]", "=", "'--format=json'", ";", "$", "modules", "=", "$", "this", "->", "__call", "(", "'pmList'", ",", "[", "]", ")", ";", "if", "(", "!", "$", "modules", "=", "json_decode", "(", "$", "modules", ",", "TRUE", ")", ")", "{", "throw", "new", "DrushFormatException", "(", "\"Cannot parse json output from drush: $modules\"", ",", "$", "modules", ")", ";", "}", "$", "this", "->", "options", "=", "[", "]", ";", "return", "isset", "(", "$", "modules", "[", "$", "name", "]", ")", "&&", "$", "modules", "[", "$", "name", "]", "[", "'status'", "]", "===", "'Enabled'", ";", "}" ]
Determine if a module is enabled or not. @param $name The machine name of the module to check. @return bool Whether the module is enabled or not. @throws DrushFormatException
[ "Determine", "if", "a", "module", "is", "enabled", "or", "not", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Driver/DrushDriver.php#L203-L211
drutiny/drutiny
src/Driver/DrushDriver.php
DrushDriver.configSet
public function configSet($collection, $key, $value) { $value = base64_encode(Yaml::dump($value)); if ($index = array_search('--format=json', $this->options)) { unset($this->options[$index]); } $this->options[] = '--format=yaml'; $this->options[] = '-y'; $pipe = "echo '$value' | base64 --decode |"; $this->runCommand('config-set', [ $collection, $key, '-' ], $pipe); return TRUE; }
php
public function configSet($collection, $key, $value) { $value = base64_encode(Yaml::dump($value)); if ($index = array_search('--format=json', $this->options)) { unset($this->options[$index]); } $this->options[] = '--format=yaml'; $this->options[] = '-y'; $pipe = "echo '$value' | base64 --decode |"; $this->runCommand('config-set', [ $collection, $key, '-' ], $pipe); return TRUE; }
[ "public", "function", "configSet", "(", "$", "collection", ",", "$", "key", ",", "$", "value", ")", "{", "$", "value", "=", "base64_encode", "(", "Yaml", "::", "dump", "(", "$", "value", ")", ")", ";", "if", "(", "$", "index", "=", "array_search", "(", "'--format=json'", ",", "$", "this", "->", "options", ")", ")", "{", "unset", "(", "$", "this", "->", "options", "[", "$", "index", "]", ")", ";", "}", "$", "this", "->", "options", "[", "]", "=", "'--format=yaml'", ";", "$", "this", "->", "options", "[", "]", "=", "'-y'", ";", "$", "pipe", "=", "\"echo '$value' | base64 --decode |\"", ";", "$", "this", "->", "runCommand", "(", "'config-set'", ",", "[", "$", "collection", ",", "$", "key", ",", "'-'", "]", ",", "$", "pipe", ")", ";", "return", "TRUE", ";", "}" ]
Override config-set to allow better value setting. @param $collection @param $key @param $value @return bool
[ "Override", "config", "-", "set", "to", "allow", "better", "value", "setting", "." ]
train
https://github.com/drutiny/drutiny/blob/ba16557024f36e0f2f1612aae7f35cac9f460d81/src/Driver/DrushDriver.php#L221-L237