_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q266900
Tokenizer.getStatedClassInstanceToken
test
public function getStatedClassInstanceToken(LifeCyclableInterface $object): string { $statedClassName = \get_class($object); return $this->getStatedClassNameToken($statedClassName, true); }
php
{ "resource": "" }
q266901
PEAR_REST_11.listCategory
test
function listCategory($base, $category, $info = false, $channel = false) { if ($info == false) { $url = '%s'.'c/%s/packages.xml'; } else { $url = '%s'.'c/%s/packagesinfo.xml'; } $url = sprintf($url, $base, urlencode($category)); // gives '404 Not Found' error when category doesn't exist $packagelist = $this->_rest->retrieveData($url, false, false, $channel); if (PEAR::isError($packagelist)) { return $packagelist; } if (!is_array($packagelist)) { return array(); } if ($info == false) { if (!isset($packagelist['p'])) { return array(); } if (!is_array($packagelist['p']) || !isset($packagelist['p'][0])) { // only 1 pkg $packagelist = array($packagelist['p']); } else { $packagelist = $packagelist['p']; } return $packagelist; } // info == true if (!isset($packagelist['pi'])) { return array(); } if (!is_array($packagelist['pi']) || !isset($packagelist['pi'][0])) { // only 1 pkg $packagelist_pre = array($packagelist['pi']); } else { $packagelist_pre = $packagelist['pi']; } $packagelist = array(); foreach ($packagelist_pre as $i => $item) { // compatibility with r/<latest.txt>.xml if (isset($item['a']['r'][0])) { // multiple releases $item['p']['v'] = $item['a']['r'][0]['v']; $item['p']['st'] = $item['a']['r'][0]['s']; } elseif (isset($item['a'])) { // first and only release $item['p']['v'] = $item['a']['r']['v']; $item['p']['st'] = $item['a']['r']['s']; } $packagelist[$i] = array('attribs' => $item['p']['r'], '_content' => $item['p']['n'], 'info' => $item['p']); } return $packagelist; }
php
{ "resource": "" }
q266902
PEAR_REST_11.betterStates
test
function betterStates($state, $include = false) { static $states = array('snapshot', 'devel', 'alpha', 'beta', 'stable'); $i = array_search($state, $states); if ($i === false) { return false; } if ($include) { $i--; } return array_slice($states, $i + 1); }
php
{ "resource": "" }
q266903
Executioner.compileCommand
test
private function compileCommand() { $command = ''; if ($this->sudo) { $command = 'sudo '; } $command .= escapeshellcmd($this->applicationPath) . $this->generateArguments(); if ($this->stdError) { $command .= ' 2>&1'; } return $command; }
php
{ "resource": "" }
q266904
Executioner.generateArguments
test
protected function generateArguments() { $arguments = ''; if (!$this->applicationArguments->isEmpty()) { $arguments = ' ' . $this->applicationArguments->implode(); } return $arguments; }
php
{ "resource": "" }
q266905
Executioner.executeProcess
test
private function executeProcess() { $command = $this->compileCommand(); exec($command, $result, $status); if ($status > 0) { throw new Exceptions\ExecutionException('Unknown error occurred when attempting to execute: ' . $command . PHP_EOL); } return $result; }
php
{ "resource": "" }
q266906
FileManager.save
test
private function save() { foreach ($this->stream as $key => $file) { $layer = ucwords($key); $namespace = Text::replace($this->namespace, '\\', '/'); $root = Text::replace("{$this->directory}/{$namespace}/{$layer}", '//', '/'); $success = true; if (!Directory::exists($root)) { $success = Directory::make($root); } if (!$success) { return false; } $class = $this->class . (($key !== 'model') ? $layer : ''); $filename = "{$root}/{$class}.php"; return !!File::write($filename, $file); } return false; }
php
{ "resource": "" }
q266907
FileManager.replace
test
private function replace() { foreach ($this->stream as &$content) { foreach ($this->replacements as $field) { $content = Text::replace($content, $field['field'], $field['value']); } } return $this->stream; }
php
{ "resource": "" }
q266908
NativeRouter.addRoute
test
public function addRoute(Route $route): void { // Verify the dispatch $this->app->dispatcher()->verifyDispatch($route); // Set the path to the validated cleaned path (/some/path) $route->setPath($this->validatePath($route->getPath())); // Ensure the request methods are set $route->getRequestMethods(); // If this is a dynamic route if ($route->isDynamic()) { // Set the dynamic route's properties through the path parser $this->setDynamicRoute($route); } // Set the route in the collection self::$collection->addRoute($route); }
php
{ "resource": "" }
q266909
NativeRouter.get
test
public function get(Route $route): void { $route->setRequestMethods([RequestMethod::GET, RequestMethod::HEAD]); $this->addRoute($route); }
php
{ "resource": "" }
q266910
NativeRouter.post
test
public function post(Route $route): void { $route->setRequestMethods([RequestMethod::POST]); $this->addRoute($route); }
php
{ "resource": "" }
q266911
NativeRouter.put
test
public function put(Route $route): void { $route->setRequestMethods([RequestMethod::PUT]); $this->addRoute($route); }
php
{ "resource": "" }
q266912
NativeRouter.patch
test
public function patch(Route $route): void { $route->setRequestMethods([RequestMethod::PATCH]); $this->addRoute($route); }
php
{ "resource": "" }
q266913
NativeRouter.delete
test
public function delete(Route $route): void { $route->setRequestMethods([RequestMethod::DELETE]); $this->addRoute($route); }
php
{ "resource": "" }
q266914
NativeRouter.head
test
public function head(Route $route): void { $route->setRequestMethods([RequestMethod::HEAD]); $this->addRoute($route); }
php
{ "resource": "" }
q266915
NativeRouter.route
test
public function route(string $name): Route { // If no route was found if (! $this->routeIsset($name)) { throw new InvalidRouteName($name); } return self::$collection->namedRoute($name); }
php
{ "resource": "" }
q266916
NativeRouter.routeUrl
test
public function routeUrl(string $name, array $data = null, bool $absolute = null): string { // Get the matching route $route = $this->route($name); // Set the host to use if this is an absolute url // or the config is set to always use absolute urls // or the route is secure (needs https:// appended) $host = $absolute || $this->app->config()['routing']['useAbsoluteUrls'] || $route->isSecure() ? $this->routeHost($route) : ''; // Get the path from the generator $path = $route->getSegments() ? $this->app->pathGenerator()->parse( $route->getSegments(), $data, $route->getParams() ) : $route->getPath(); return $host . $this->validateRouteUrl($path); }
php
{ "resource": "" }
q266917
NativeRouter.requestRoute
test
public function requestRoute(Request $request): ? Route { $requestMethod = $request->getMethod(); // Decode the request uri $requestUri = rawurldecode($request->getPathOnly()); return $this->matchRoute($requestUri, $requestMethod); }
php
{ "resource": "" }
q266918
NativeRouter.matchRoute
test
public function matchRoute(string $path, string $method = null): ? Route { // Validate the path $path = $this->validatePath($path); $method = $method ?? RequestMethod::GET; if (null !== $route = $this->matchStaticRoute($path, $method)) { return $route; } return $this->matchDynamicRoute($path, $method); }
php
{ "resource": "" }
q266919
NativeRouter.isInternalUri
test
public function isInternalUri(string $uri): bool { // Replace the scheme if it exists $uri = str_replace(['http://', 'https://'], '', $uri); // Get the host of the uri $host = (string) substr($uri, 0, strpos($uri, '/')); // If the host does not match the current request uri's host if ($host && $host !== $this->app->request()->getHttpHost()) { // Return false immediately return false; } // Get only the path (full string from the first slash to the end // of the path) $uri = (string) substr($uri, strpos($uri, '/'), \count($uri)); // Try to match the route $route = $this->matchRoute($uri); return $route instanceof Route; }
php
{ "resource": "" }
q266920
NativeRouter.dispatch
test
public function dispatch(Request $request): Response { // Check the returned route if (null === $route = $this->requestRoute($request)) { // If it was null throw a not found exception throw new NotFoundHttpException(); } // If the route is secure and the current request is not secure if ($route->isSecure() && ! $request->isSecure()) { // Throw the redirect to the secure path return $this->app->redirect()->secure($request->getPath()); } // Dispatch the route's before request handled middleware $middlewareReturn = $this->routeRequestMiddleware($request, $route); // If the middleware returned a response if ($middlewareReturn instanceof Response) { // Return the response return $middlewareReturn; } // Trigger an event for route matched $this->app->events()->trigger(RouteMatched::class, [$route, $request]); // Set the found route in the service container $this->app->container()->singleton(Route::class, $route); // Attempt to dispatch the route using any one of the callable options $dispatch = $this->app->dispatcher()->dispatchCallable( $route, $route->getMatches() ); // Get the response from the dispatch $response = $this->getResponseFromDispatch($dispatch); // Dispatch the route's before request handled middleware and return // the response $this->routeResponseMiddleware($request, $response, $route); return $response; }
php
{ "resource": "" }
q266921
NativeRouter.setup
test
public function setup(bool $force = false, bool $useCache = true): void { // If route's have already been setup, no need to do it again if (self::$setup && ! $force) { return; } self::$setup = true; // If the application should use the routes cache file if ($useCache && $this->app->config()['routing']['useCache']) { $this->setupFromCache(); // Then return out of setup return; } self::$collection = new RouteCollection(); // If annotations are enabled and routing should use annotations if ( $this->app->config()['routing']['useAnnotations'] && $this->app->config()['annotations']['enabled'] ) { // Setup annotated routes $this->setupAnnotatedRoutes(); // If only annotations should be used for routing if ($this->app->config()['routing']['useAnnotationsExclusively']) { // Return to avoid loading routes file return; } } // Include the routes file // NOTE: Included if annotations are set or not due to possibility of // routes being defined within the controllers as well as within the // routes file require $this->app->config()['routing']['filePath']; }
php
{ "resource": "" }
q266922
NativeRouter.setDynamicRoute
test
protected function setDynamicRoute(Route $route): void { // Parse the path $parsedRoute = $this->app->pathParser()->parse($route->getPath()); // Set the properties $route->setRegex($parsedRoute['regex']); $route->setParams($parsedRoute['params']); $route->setSegments($parsedRoute['segments']); }
php
{ "resource": "" }
q266923
NativeRouter.validateRouteUrl
test
protected function validateRouteUrl(string $path): string { // If the last character is not a slash and the config is set to // ensure trailing slash if ( $path[-1] !== '/' && $this->app->config()['routing']['trailingSlash'] ) { // add a trailing slash $path .= '/'; } return $path; }
php
{ "resource": "" }
q266924
NativeRouter.matchStaticRoute
test
protected function matchStaticRoute(string $path, string $method): ? Route { $route = null; // Let's check if the route is set in the static routes if (self::$collection->issetStaticRoute($method, $path)) { $route = $this->getMatchedStaticRoute($path, $method); } if (null !== $route && $this->isValidMethod($route, $method)) { return $route; } return null; }
php
{ "resource": "" }
q266925
NativeRouter.matchDynamicRoute
test
protected function matchDynamicRoute(string $path, string $method): ? Route { // The route to return (null by default) $route = null; // The dynamic routes $dynamicRoutes = self::$collection->getDynamicRoutes($method); // Attempt to find a match using dynamic routes that are set foreach ($dynamicRoutes as $regex => $dynamicRoute) { // If the preg match is successful, we've found our route! /* @var array $matches */ if (preg_match($regex, $path, $matches)) { $route = $this->getMatchedDynamicRoute($dynamicRoute, $matches, $method); break; } } // If the route was found and the method is valid if (null !== $route && $this->isValidMethod($route, $method)) { // Return the route return $route; } return null; }
php
{ "resource": "" }
q266926
NativeRouter.getMatchedStaticRoute
test
protected function getMatchedStaticRoute(string $path, string $method): Route { return clone self::$collection->staticRoute($method, $path); }
php
{ "resource": "" }
q266927
NativeRouter.getMatchedDynamicRoute
test
protected function getMatchedDynamicRoute(string $path, array $matches, string $method): Route { // Clone the route to avoid changing the one set in the master array $dynamicRoute = clone self::$collection->dynamicRoute($method, $path); // The first match is the path itself unset($matches[0]); // Iterate through the matches foreach ($matches as $key => $match) { // If there is no match (middle of regex optional group) if (! $match) { // Set the value to null so the controller's action // can use the default it sets $matches[$key] = null; } } // Set the matches $dynamicRoute->setMatches($matches); return $dynamicRoute; }
php
{ "resource": "" }
q266928
NativeRouter.routeRequestMiddleware
test
protected function routeRequestMiddleware(Request $request, Route $route) { // If the route has no middleware if (null === $route->getMiddleware()) { // Return the request passed through return $request; } return $this->app->kernel()->requestMiddleware( $request, $route->getMiddleware() ); }
php
{ "resource": "" }
q266929
NativeRouter.routeResponseMiddleware
test
protected function routeResponseMiddleware(Request $request, Response $response, Route $route): void { // If the route has no middleware if (null === $route->getMiddleware()) { // Return the response passed through return; } $this->app->kernel()->responseMiddleware( $request, $response, $route->getMiddleware() ); }
php
{ "resource": "" }
q266930
NativeRouter.getResponseFromDispatch
test
protected function getResponseFromDispatch($dispatch): Response { // If the dispatch failed, 404 if (! $dispatch) { $this->app->abort(); } // If the dispatch is a Response then simply return it if ($dispatch instanceof Response) { return $dispatch; } // If the dispatch is a View, render it then wrap it in a new response // and return it if ($dispatch instanceof View) { return $this->app->response($dispatch->render()); } // Otherwise its a string so wrap it in a new response and return it return $this->app->response((string) $dispatch); }
php
{ "resource": "" }
q266931
NativeRouter.setupFromCache
test
protected function setupFromCache(): void { // Set the application routes with said file $cache = $this->app->config()['cache']['routing'] ?? require $this->app->config()['routing']['cacheFilePath']; self::$collection = unserialize( base64_decode($cache['collection'], true), [ 'allowed_classes' => [ RouteCollection::class, Route::class, ], ] ); }
php
{ "resource": "" }
q266932
NativeRouter.setupAnnotatedRoutes
test
protected function setupAnnotatedRoutes(): void { /** @var RouteAnnotations $routeAnnotations */ $routeAnnotations = $this->app->container()->getSingleton( RouteAnnotations::class ); // Get all the annotated routes from the list of controllers $routes = $routeAnnotations->getRoutes( ...$this->app->config()['routing']['controllers'] ); // Iterate through the routes foreach ($routes as $route) { // Set the route $this->addRoute($route); } }
php
{ "resource": "" }
q266933
Modal.renderHeader
test
protected function renderHeader() { $button = $this->renderCloseButton(); if ($button !== null) { $this->header = $this->header . "\n" . $button; } if ($this->header !== null) { Html::addCssClass($this->headerOptions, ['widget' => 'modal-header']); return $this->htmlHlp->tag('div', "\n" . $this->header . "\n", $this->headerOptions); } else { return null; } }
php
{ "resource": "" }
q266934
Modal.renderToggleButton
test
protected function renderToggleButton() { if (($toggleButton = $this->toggleButton) !== false) { $tag = ArrayHelper::remove($toggleButton, 'tag', 'button'); $label = ArrayHelper::remove($toggleButton, 'label', 'Show'); if ($tag === 'button' && !isset($toggleButton['type'])) { $toggleButton['type'] = 'button'; } return $this->htmlHlp->tag($tag, $label, $toggleButton); } else { return null; } }
php
{ "resource": "" }
q266935
GettextMessageSource.getGettextFile
test
protected function getGettextFile($messageFile) { if (isset($this->_gettextFiles[$messageFile])) { return $this->_gettextFiles[$messageFile]; } if (!is_file($messageFile)) { return null; } if ($this->useMoFile) { $gettextFile = new GettextMoFile(['filePath' => $messageFile, 'useBigEndian' => $this->useBigEndian]); } else { $gettextFile = new GettextPoFile(['filePath' => $messageFile]); } return $this->_gettextFiles[$messageFile] = $gettextFile; }
php
{ "resource": "" }
q266936
DQL.getQBResult
test
protected function getQBResult(Params $params, Query $query) { $paginated = new Paginator($query); $paginated->setUseOutputWalkers(false); $this->setTotal($paginated->count()); return $paginated; }
php
{ "resource": "" }
q266937
DQL.addFilters
test
protected function addFilters(Params $params, QueryBuilder $qb) { $this->filterByIdentifier($params, $qb) ->filterBySearch($params, $qb); return $this; }
php
{ "resource": "" }
q266938
DQL.filterBySearch
test
protected function filterBySearch(Params $params, QueryBuilder $qb) { if ($query = $params->getWrapped('search')->get('value')) { $this->searchFilter($params, $qb, $query); } return $this; }
php
{ "resource": "" }
q266939
DQL.searchFilter
test
protected function searchFilter(Params $params, QueryBuilder $qb, $search) { $qb->andWhere($this->alias('id').' LIKE :search')->setParameter('search', $search); return $this; }
php
{ "resource": "" }
q266940
DQL.addOrdering
test
protected function addOrdering(Params $params, QueryBuilder $qb) { $orderDir = "ASC"; if ($params->has('orderDir') && (strtoupper($params->get('orderDir')) == "DESC")) { $orderDir = "DESC"; } if ($params->has('orderBy') && $params->get('orderBy') != "") { $qb->orderBy($this->alias($params->get('orderBy')), $orderDir); } return $this; }
php
{ "resource": "" }
q266941
DQL.addOffset
test
protected function addOffset(Params $params, QueryBuilder $qb) { if ($this->getOffset() && $this->getOffset() > 0) { $qb->setFirstResult($this->getOffset()); } return $this; }
php
{ "resource": "" }
q266942
DQL.addLimit
test
protected function addLimit(Params $params, QueryBuilder $qb) { if ($this->getLimit() && $this->getLimit() > 0) { $qb->setMaxResults($this->getLimit()); } return $this; }
php
{ "resource": "" }
q266943
DQL.find
test
public function find($id) { $params = Params::create(array($this->getIdParam() => $id, 'limit' => 1)); $qb = $this->getCustomizedQueryBuilder($params); $results = $this->getQBResult($params, $this->queryHook($params, $qb)); if ($results->count() != 1) { throw new NotFound("Unable to locate entity ".$this->getRepository()." with id ".$id); } /* @var $results \Doctrine\ORM\Tools\Pagination\Paginator */ /** * Note: this is a paginator object so the only way to access result elements is by iterating */ foreach ($results as $result) { // return the first (and only) result return $result; } }
php
{ "resource": "" }
q266944
DQL.safeJoin
test
public function safeJoin(QueryBuilder $qb, $property, $joinedAlias, $autoAlias = true) { if ($autoAlias) { $property = $this->alias($property); } if (!isset($this->joinMap[$property])) { $qb->join($property, $joinedAlias); $this->joinMap[$property] = $joinedAlias; } return $this; }
php
{ "resource": "" }
q266945
DQL.getDataTablesSortColumn
test
protected function getDataTablesSortColumn(Params $params) { $column = $params->getWrapped('order')->getWrapped(0)->get('column', 0); return $params->getWrapped('columns')->getWrapped($column)->get('data'); }
php
{ "resource": "" }
q266946
DQL.orderByDataTablesParams
test
protected function orderByDataTablesParams(Params $params, QueryBuilder $qb) { $order = $this->getDataTablesSortOrder($params); $sort = $this->getDataTablesSortColumn($params); if ($sort) { $qb->addOrderBy($this->alias($sort), $order); } return $this; }
php
{ "resource": "" }
q266947
PhoneValidator.isValid
test
public function isValid($value, Constraint $constraint) { if (empty($value)) { return true; } $ret = $this->validateNumber($value, $constraint->format); if (!$ret) { $this->setMessage($constraint->message); } return $ret; }
php
{ "resource": "" }
q266948
XML_Util.replaceEntities
test
function replaceEntities($string, $replaceEntities = XML_UTIL_ENTITIES_XML, $encoding = 'ISO-8859-1') { switch ($replaceEntities) { case XML_UTIL_ENTITIES_XML: return strtr($string, array( '&' => '&amp;', '>' => '&gt;', '<' => '&lt;', '"' => '&quot;', '\'' => '&apos;' )); break; case XML_UTIL_ENTITIES_XML_REQUIRED: return strtr($string, array( '&' => '&amp;', '<' => '&lt;', '"' => '&quot;' )); break; case XML_UTIL_ENTITIES_HTML: return htmlentities($string, ENT_COMPAT, $encoding); break; } return $string; }
php
{ "resource": "" }
q266949
XML_Util.reverseEntities
test
function reverseEntities($string, $replaceEntities = XML_UTIL_ENTITIES_XML, $encoding = 'ISO-8859-1') { switch ($replaceEntities) { case XML_UTIL_ENTITIES_XML: return strtr($string, array( '&amp;' => '&', '&gt;' => '>', '&lt;' => '<', '&quot;' => '"', '&apos;' => '\'' )); break; case XML_UTIL_ENTITIES_XML_REQUIRED: return strtr($string, array( '&amp;' => '&', '&lt;' => '<', '&quot;' => '"' )); break; case XML_UTIL_ENTITIES_HTML: return html_entity_decode($string, ENT_COMPAT, $encoding); break; } return $string; }
php
{ "resource": "" }
q266950
XML_Util.getXMLDeclaration
test
function getXMLDeclaration($version = '1.0', $encoding = null, $standalone = null) { $attributes = array( 'version' => $version, ); // add encoding if ($encoding !== null) { $attributes['encoding'] = $encoding; } // add standalone, if specified if ($standalone !== null) { $attributes['standalone'] = $standalone ? 'yes' : 'no'; } return sprintf('<?xml%s?>', XML_Util::attributesToString($attributes, false)); }
php
{ "resource": "" }
q266951
XML_Util.getDocTypeDeclaration
test
function getDocTypeDeclaration($root, $uri = null, $internalDtd = null) { if (is_array($uri)) { $ref = sprintf(' PUBLIC "%s" "%s"', $uri['id'], $uri['uri']); } elseif (!empty($uri)) { $ref = sprintf(' SYSTEM "%s"', $uri); } else { $ref = ''; } if (empty($internalDtd)) { return sprintf('<!DOCTYPE %s%s>', $root, $ref); } else { return sprintf("<!DOCTYPE %s%s [\n%s\n]>", $root, $ref, $internalDtd); } }
php
{ "resource": "" }
q266952
XML_Util.attributesToString
test
function attributesToString($attributes, $sort = true, $multiline = false, $indent = ' ', $linebreak = "\n", $entities = XML_UTIL_ENTITIES_XML) { /* * second parameter may be an array */ if (is_array($sort)) { if (isset($sort['multiline'])) { $multiline = $sort['multiline']; } if (isset($sort['indent'])) { $indent = $sort['indent']; } if (isset($sort['linebreak'])) { $multiline = $sort['linebreak']; } if (isset($sort['entities'])) { $entities = $sort['entities']; } if (isset($sort['sort'])) { $sort = $sort['sort']; } else { $sort = true; } } $string = ''; if (is_array($attributes) && !empty($attributes)) { if ($sort) { ksort($attributes); } if ( !$multiline || count($attributes) == 1) { foreach ($attributes as $key => $value) { if ($entities != XML_UTIL_ENTITIES_NONE) { if ($entities === XML_UTIL_CDATA_SECTION) { $entities = XML_UTIL_ENTITIES_XML; } $value = XML_Util::replaceEntities($value, $entities); } $string .= ' ' . $key . '="' . $value . '"'; } } else { $first = true; foreach ($attributes as $key => $value) { if ($entities != XML_UTIL_ENTITIES_NONE) { $value = XML_Util::replaceEntities($value, $entities); } if ($first) { $string .= ' ' . $key . '="' . $value . '"'; $first = false; } else { $string .= $linebreak . $indent . $key . '="' . $value . '"'; } } } } return $string; }
php
{ "resource": "" }
q266953
XML_Util.collapseEmptyTags
test
function collapseEmptyTags($xml, $mode = XML_UTIL_COLLAPSE_ALL) { if ($mode == XML_UTIL_COLLAPSE_XHTML_ONLY) { return preg_replace( '/<(area|base(?:font)?|br|col|frame|hr|img|input|isindex|link|meta|' . 'param)([^>]*)><\/\\1>/s', '<\\1\\2 />', $xml); } else { return preg_replace('/<(\w+)([^>]*)><\/\\1>/s', '<\\1\\2 />', $xml); } }
php
{ "resource": "" }
q266954
XML_Util.createTag
test
function createTag($qname, $attributes = array(), $content = null, $namespaceUri = null, $replaceEntities = XML_UTIL_REPLACE_ENTITIES, $multiline = false, $indent = '_auto', $linebreak = "\n", $sortAttributes = true) { $tag = array( 'qname' => $qname, 'attributes' => $attributes ); // add tag content if ($content !== null) { $tag['content'] = $content; } // add namespace Uri if ($namespaceUri !== null) { $tag['namespaceUri'] = $namespaceUri; } return XML_Util::createTagFromArray($tag, $replaceEntities, $multiline, $indent, $linebreak, $sortAttributes); }
php
{ "resource": "" }
q266955
XML_Util.createStartElement
test
function createStartElement($qname, $attributes = array(), $namespaceUri = null, $multiline = false, $indent = '_auto', $linebreak = "\n", $sortAttributes = true) { // if no attributes hav been set, use empty attributes if (!isset($attributes) || !is_array($attributes)) { $attributes = array(); } if ($namespaceUri != null) { $parts = XML_Util::splitQualifiedName($qname); } // check for multiline attributes if ($multiline === true) { if ($indent === '_auto') { $indent = str_repeat(' ', (strlen($qname)+2)); } } if ($namespaceUri != null) { // is a namespace given if (isset($parts['namespace']) && !empty($parts['namespace'])) { $attributes['xmlns:' . $parts['namespace']] = $namespaceUri; } else { // define this Uri as the default namespace $attributes['xmlns'] = $namespaceUri; } } // create attribute list $attList = XML_Util::attributesToString($attributes, $sortAttributes, $multiline, $indent, $linebreak); $element = sprintf('<%s%s>', $qname, $attList); return $element; }
php
{ "resource": "" }
q266956
XML_Util.splitQualifiedName
test
function splitQualifiedName($qname, $defaultNs = null) { if (strstr($qname, ':')) { $tmp = explode(':', $qname); return array( 'namespace' => $tmp[0], 'localPart' => $tmp[1] ); } return array( 'namespace' => $defaultNs, 'localPart' => $qname ); }
php
{ "resource": "" }
q266957
XML_Util.isValidName
test
function isValidName($string) { // check for invalid chars if (!preg_match('/^[[:alpha:]_]$/', $string{0})) { return XML_Util::raiseError('XML names may only start with letter ' . 'or underscore', XML_UTIL_ERROR_INVALID_START); } // check for invalid chars if (!preg_match('/^([[:alpha:]_]([[:alnum:]\-\.]*)?:)?[[:alpha:]_]([[:alnum:]\_\-\.]+)?$/', $string) ) { return XML_Util::raiseError('XML names may only contain alphanumeric ' . 'chars, period, hyphen, colon and underscores', XML_UTIL_ERROR_INVALID_CHARS); } // XML name is valid return true; }
php
{ "resource": "" }
q266958
Call.dispatch
test
public static function dispatch(ICallable $object) { $params = $object->getParams(); $call = $object->getCallable(); if (!is_callable($call)) { throw new CallException("Non callable object found"); } if ($call instanceof Closure) { return call_user_func_array($call, $params); } $class = explode('::', $call); $reflection = new ReflectionClass($class[0]); $method = $reflection->getMethod($class[1]); if ($method->isStatic()) { return call_user_func_array($call, $params); } return call_user_func_array(array(new $class[0], $class[1]), $params); }
php
{ "resource": "" }
q266959
HttpCacheEventSubscriber.onTagResponse
test
public function onTagResponse(HttpCacheEvent $event) { $tags = $event->getData(); if (empty($tags)) { return; } $this->tagManager->addTags($tags); }
php
{ "resource": "" }
q266960
HttpCacheEventSubscriber.onInvalidateTag
test
public function onInvalidateTag(HttpCacheEvent $event) { $tags = $event->getData(); if (empty($tags)) { return; } $this->tagManager->invalidateTags($tags); }
php
{ "resource": "" }
q266961
ValidationSubscriber.validate
test
protected function validate(LifecycleEventArgs $args) { $entity = $args->getEntity(); $metadata = $args->getEntityManager()->getClassMetadata(get_class($entity)); if($this->shouldBeValidated($entity)) { $rules = $entity->getValidationRules(); $fields = $metadata->getFieldNames(); $data = []; foreach($fields as $field) { $data[$field] = $metadata->getFieldValue($entity, $field); } $this->validator->with($data, $rules); if(!$this->validator->passes()) { throw new InvalidEntityException($entity, $this->validator->errors()); } } }
php
{ "resource": "" }
q266962
MessageInterpolationTrait.interpolateMessage
test
protected function interpolateMessage($message, array $context)//@codingStandardsIgnoreLine Ignore missing type hint { $context = array_filter( $context, function ($value) { return (is_scalar($value) || (is_object($value) && method_exists($value, '__toString'))); } ); $search = []; $replace = []; foreach ($context as $key => $value) { $search[] = "{{$key}}"; $replace[] = (string)$value; } return str_replace($search, $replace, $message); }
php
{ "resource": "" }
q266963
Maths.areSameSpace
test
public static function areSameSpace(PointInterface $point1, PointInterface $point2) { return (bool) ( ($point1->is1D() && $point2->is1d()) || ($point1->is2D() && $point2->is2d()) || ($point1->is3D() && $point2->is3d()) ); }
php
{ "resource": "" }
q266964
Maths.areSamePoint
test
public static function areSamePoint(PointInterface $point1, PointInterface $point2) { if (self::areSameSpace($point1, $point2)) { if ($point1->is1D()) { return (bool) ($point1->getAbscissa()==$point2->getAbscissa()); } elseif ($point1->is2D()) { return (bool) ( ($point1->getAbscissa()==$point2->getAbscissa()) && ($point1->getOrdinate()==$point2->getOrdinate()) ); } elseif ($point1->is3D()) { return (bool) ( ($point1->getAbscissa()==$point2->getAbscissa()) && ($point1->getOrdinate()==$point2->getOrdinate()) && ($point1->getApplicate()==$point2->getApplicate()) ); } } else { throw new \InvalidArgumentException( "Can not compare positions of two points of different space types" ); } }
php
{ "resource": "" }
q266965
Maths.getLinesIntersection
test
public static function getLinesIntersection(Line $line1, Line $line2) { $div = ($line1->getSlope() - $line2->getSlope()); $x = ($div!=0 ? (($line2->getYIntercept() - $line1->getYIntercept()) / $div) : ($line2->getYIntercept() - $line1->getYIntercept())); $y = $line1->getOrdinateByAbscissa($x); return new Point($x, $y); }
php
{ "resource": "" }
q266966
Maths.arePerpendiculars
test
public function arePerpendiculars(Line $line1, Line $line2) { if (self::areParallels($line1, $line2)) { return false; } }
php
{ "resource": "" }
q266967
Maths.areParallels
test
public static function areParallels(Line $line1, Line $line2) { if ( ($line1->isHorizontal() && $line2->isHorizontal()) || ($line1->isVertical() && $line2->isVertical()) ) { return true; } $line1->rearrange(); $line2->rearrange(); $abs = array( $line1->getPointA()->getAbscissa(), $line1->getPointB()->getAbscissa(), $line2->getPointA()->getAbscissa(), $line2->getPointB()->getAbscissa() ); $ords = array( $line1->getPointA()->getOrdinate(), $line1->getPointB()->getOrdinate(), $line2->getPointA()->getOrdinate(), $line2->getPointB()->getOrdinate() ); $e = new Point( rand(0, 10) + (max($abs) + abs(min($abs))), rand(0, 10) + (max($ords) + abs(min($ords))) ); $segAE = new Segment($line1->getPointA(), $e); $segBE = new Segment($line1->getPointB(), $e); $intersectCE = self::getLinesIntersection($segAE, $line2); $segCE = new Segment($intersectCE, $e); $intersectDE = self::getLinesIntersection($segBE, $line2); $segDE = new Segment($intersectDE, $e); /* echo <<<TYPEOTHER var demo1 = brd.create('point', [{$line1->getPointA()->x},{$line1->getPointA()->y}], { name: 'a' }); var demo2 = brd.create('point', [{$line1->getPointB()->x},{$line1->getPointB()->y}], { name: 'b' }); var segment1 = brd.create('line', [demo1,demo2], {straightFirst:false,straightLast:false}); var demo3 = brd.create('point', [{$intersectCE->x},{$intersectCE->y}], { name: 'c' }); var demo4 = brd.create('point', [{$intersectDE->x},{$intersectDE->y}], { name: 'd' }); var segment2 = brd.create('line', [demo3,demo4], {straightFirst:false,straightLast:false}); var demo5 = brd.create('point', [{$e->x},{$e->y}], { name: 'e' }); var segment3 = brd.create('line', [demo1,demo5], {straightFirst:false,straightLast:false,color:'#404040'}); var segment4 = brd.create('line', [demo2,demo5], {straightFirst:false,straightLast:false,color:'#404040'}); var segment5 = brd.create('line', [demo3,demo5], {straightFirst:false,straightLast:false,color:'#404040'}); var segment6 = brd.create('line', [demo4,demo5], {straightFirst:false,straightLast:false,color:'#404040'}); TYPEOTHER; */ return (bool) (($segAE->getLength() / $segCE->getLength()) == ($segBE->getLength() / $segDE->getLength())); }
php
{ "resource": "" }
q266968
Maths.getDirectionByPoints
test
public static function getDirectionByPoints(PointInterface $point1, PointInterface $point2) { if (self::areSameSpace($point1, $point2)) { $directions = array( 0 => self::getDirectionByCoordinates($point1->getAbscissa(), $point2->getAbscissa()) ); if ($point1->is2D() || $point1->is3D()) { $directions[1] = self::getDirectionByCoordinates($point1->getOrdinate(), $point2->getOrdinate()); } if ($point1->is3D()) { $directions[2] = self::getDirectionByCoordinates($point1->getApplicate(), $point2->getApplicate()); } return $directions; } else { throw new \InvalidArgumentException( "Can not guess directions between two points of different space types" ); } }
php
{ "resource": "" }
q266969
Maths.getDirectionByCoordinates
test
public static function getDirectionByCoordinates($a, $b) { if ($a < $b) { return self::DIRECTION_POSITIVE; } elseif ($a > $b) { return self::DIRECTION_NEGATIVE; } else { return self::DIRECTION_NULL; } }
php
{ "resource": "" }
q266970
ActiveQuery.all
test
public function all($db = null) { if ($this->emulateExecution) { return resolve([]); } return $this->createCommand($db)->thenLazy( function(CommandInterface $command) { return $command->queryAll(); } )->thenLazy( function($results) { return $this->populate($results); } ); }
php
{ "resource": "" }
q266971
ActiveQuery.prepareAsyncVia
test
protected function prepareAsyncVia() { // lazy loading of a relation $where = $this->where; $promise = new LazyPromise(function() { return resolve(true); }); if ($this->via instanceof self) { // via junction table $promise->thenLazy( function() { return $this->via->findJunctionRows([$this->primaryModel]); } )->thenLazy( function($viaModels) { $this->filterByModels($viaModels); return true; } ); } elseif (is_array($this->via)) { // via relation /* @var $viaQuery ActiveQuery */ list($viaName, $viaQuery) = $this->via; $viaModelsPr = $viaQuery->multiple ? $viaQuery->all() : $viaQuery->one(); $viaModelsPr->otherwise(function() use (&$viaQuery) { return $viaQuery->multiple ? [] : null; }); $promise->thenLazy( function() use ($viaModelsPr) { return $viaModelsPr; } )->thenLazy( function($viaModels) use ($viaName, &$viaQuery) { $this->primaryModel->populateRelation($viaName, $viaModels); if (!$viaQuery->multiple) { $viaModels = $viaModels === null ? [] : [$viaModels]; } return $viaModels; } )->thenLazy( function($viaModels) { $this->filterByModels($viaModels); return true; } ); } else { $this->filterByModels([$this->primaryModel]); } return $promise->thenLazy( function() use (&$where) { $query = Query::create($this); $this->where = $where; return $query; } ); }
php
{ "resource": "" }
q266972
ActiveQuery.removeDuplicatedModels
test
private function removeDuplicatedModels($models) { $hash = []; /* @var $class ActiveRecordInterface */ $class = $this->modelClass; $pks = $class::primaryKey(); if (count($pks) > 1) { // composite primary key foreach ($models as $i => $model) { $key = []; foreach ($pks as $pk) { if (!isset($model[$pk])) { // do not continue if the primary key is not part of the result set break 2; } $key[] = $model[$pk]; } $key = serialize($key); if (isset($hash[$key])) { unset($models[$i]); } else { $hash[$key] = true; } } } elseif (empty($pks)) { throw new InvalidConfigException("Primary key of '{$class}' can not be empty."); } else { // single column primary key $pk = reset($pks); foreach ($models as $i => $model) { if (!isset($model[$pk])) { // do not continue if the primary key is not part of the result set break; } $key = $model[$pk]; if (isset($hash[$key])) { unset($models[$i]); } elseif ($key !== null) { $hash[$key] = true; } } } return array_values($models); }
php
{ "resource": "" }
q266973
ActiveQuery.one
test
public function one($db = null) { if ($this->emulateExecution) { return reject(false); } return $this->createCommand($db)->thenLazy( function(CommandInterface $command) { return $command->queryOne(); } )->thenLazy( function($row) { if ($row !== false) { return $this->populate([$row]); } return reject(null); } )->thenLazy( function($models) { return reset($models) ?: reject(null); } ); }
php
{ "resource": "" }
q266974
HeaderSecurity.isValid
test
public static function isValid(string $value): bool { // Look for: // \n not preceded by \r, OR // \r not followed by \n, OR // \r\n not followed by space or horizontal tab; these are all CRLF attacks if (preg_match("#(?:(?:(?<!\r)\n)|(?:\r(?!\n))|(?:\r\n(?![ \t])))#", $value)) { return false; } // Non-visible, non-whitespace characters // 9 === horizontal tab // 10 === line feed // 13 === carriage return // 32-126, 128-254 === visible // 127 === DEL (disallowed) // 255 === null byte (disallowed) if (preg_match('/[^\x09\x0a\x0d\x20-\x7E\x80-\xFE]/', $value)) { return false; } return true; }
php
{ "resource": "" }
q266975
HeaderSecurity.assertValid
test
public static function assertValid(string $value): void { if (! self::isValid($value)) { throw new InvalidArgumentException( sprintf( '"%s" is not valid header value', $value ) ); } }
php
{ "resource": "" }
q266976
Tunes.request
test
public function request() { if ('' !== $this->defaultOptions['callback']) { $msg = 'Cannot run query when callback is set. Get query using getRawRequestUrl().'; throw new \BadMethodCallException($msg); } $this->buildSpecificRequestUri(); try { if (null === $content = $this->getHttpClient()->getContent($this->getRawRequestUrl())) { throw new \RuntimeException('The request was not successful.'); } } catch (\RuntimeException $e) { throw new \RuntimeException('The request was not successful.'); } if (self::RESULT_ARRAY === $this->resultFormat) { $resultSet = json_decode($content, true); $resultSet = new ResultSet($resultSet['results']); return $resultSet; } else { // convert JSON-string to array $jsonString = json_decode($content); $this->resultCount = (integer) $jsonString->resultCount; $this->results = json_encode($jsonString->results); return $this->results; } }
php
{ "resource": "" }
q266977
Tunes.buildRequestUri
test
protected function buildRequestUri() { $requestParameters = array(); // add entity if (!empty($this->defaultOptions['entity'])) { $tmp = array_keys($this->defaultOptions['entity']); $key = array_pop($tmp); $requestParameters[] = 'entity=' . $this->defaultOptions['entity'][$key]; } // add media type if (!empty($this->defaultOptions['mediaType'])) { $requestParameters[] = 'media=' . $this->defaultOptions['mediaType']; } // add attribute if (!empty($this->defaultOptions['attribute'])) { $requestParameters[] = 'attribute=' . $this->defaultOptions['attribute']; } // add language if (!empty($this->defaultOptions['language'])) { $requestParameters[] = 'lang=' . $this->defaultOptions['language']; } // add limit if ($this->defaultOptions['limit'] <> 100) { $requestParameters[] = 'limit=' . $this->defaultOptions['limit']; } // add country if ($this->defaultOptions['country'] != 'us') { $requestParameters[] = 'country=' . $this->defaultOptions['country']; } // add callback if (!empty($this->defaultOptions['callback'])) { $requestParameters[] = 'callback=' . $this->defaultOptions['callback']; } // add version if ($this->defaultOptions['version'] <> 2) { $requestParameters[] = 'version=' . $this->defaultOptions['version']; } // add explicity if ($this->defaultOptions['explicit'] != 'yes') { $requestParameters[] = 'explicit=' . $this->defaultOptions['explicit']; } return implode('&', $requestParameters); }
php
{ "resource": "" }
q266978
Tunes.setLanguage
test
public function setLanguage($language = 'en_us') { if (in_array($language, $this->languageList)) { $this->defaultOptions['language'] = $language; } return $this; }
php
{ "resource": "" }
q266979
Tunes.setMediaType
test
public function setMediaType($mediatype = self::MEDIATYPE_ALL) { if (in_array($mediatype, $this->mediaTypes)) { $this->defaultOptions['mediaType'] = $mediatype; } return $this; }
php
{ "resource": "" }
q266980
Tunes.setResultFormat
test
public function setResultFormat($format = self::RESULT_ARRAY) { if (in_array($format, $this->resultFormats)) { $this->resultFormat = $format; } return $this; }
php
{ "resource": "" }
q266981
Tunes.setLimit
test
public function setLimit($limit = 100) { // the limit must be within the boundaries of the service if ($limit <= 0 || $limit > 200) { throw new \OutOfBoundsException('The limit must be within 0 and 200.'); } $this->defaultOptions['limit'] = (integer) $limit; return $this; }
php
{ "resource": "" }
q266982
Tunes.setEntity
test
public function setEntity($entity = array()) { // check if only one entry is given if (count($entity) <> 1) { throw new \InvalidArgumentException('Must be set with one key/value-pair!'); } // fetch key from parameter $_tmp = array_keys($entity); $key = array_pop($_tmp); // check if the key of the given array exists if (array_key_exists($key, $this->entityList)) { // check if value exists for key if (in_array($entity[$key], $this->entityList[$key])) { $this->defaultOptions['entity'] = $entity; } } return $this; }
php
{ "resource": "" }
q266983
Tunes.setAttribute
test
public function setAttribute($attribute = '') { if ('' === $this->defaultOptions['mediaType']) { throw new \InvalidArgumentException('Attribute relates to media type but no media type is set.'); } // check if the attribute is in the set of attributes for media type if (in_array($attribute, $this->attributesTypes[$this->defaultOptions['mediaType']])) { $this->defaultOptions['attribute'] = $attribute; } else { throw new \InvalidArgumentException('Attribute is not in the set of attributes for this media type.'); } }
php
{ "resource": "" }
q266984
Tunes.setCallback
test
public function setCallback($callback = '') { if (self::RESULT_JSON !== $this->getResultFormat()) { throw new \BadMethodCallException('Callback can only be set with RESULT_JSON'); } $this->defaultOptions['callback'] = $callback; }
php
{ "resource": "" }
q266985
Tunes.setExplicit
test
public function setExplicit($setting = 'yes') { if (in_array($setting, $this->explicitTypes)) { $this->defaultOptions['explicit'] = $setting; } return $this; }
php
{ "resource": "" }
q266986
ApiPhoto.getPhotos
test
protected function getPhotos($galleryId) { if (! is_null($ids = $this->fetchIds($galleryId))) { return array_map([$this, 'getPhoto'], $ids); } }
php
{ "resource": "" }
q266987
PEAR_Common.log
test
function log($level, $msg, $append_crlf = true) { if ($this->debug >= $level) { if (!class_exists('PEAR_Frontend')) { require_once 'PEAR/Frontend.php'; } $ui = &PEAR_Frontend::singleton(); if (is_a($ui, 'PEAR_Frontend')) { $ui->log($msg, $append_crlf); } else { print "$msg\n"; } } }
php
{ "resource": "" }
q266988
PEAR_Common.mkTempDir
test
function mkTempDir($tmpdir = '') { $topt = $tmpdir ? array('-t', $tmpdir) : array(); $topt = array_merge($topt, array('-d', 'pear')); if (!class_exists('System')) { require_once 'System.php'; } if (!$tmpdir = System::mktemp($topt)) { return false; } $this->addTempFile($tmpdir); return $tmpdir; }
php
{ "resource": "" }
q266989
PEAR_Common.infoFromTgzFile
test
function infoFromTgzFile($file) { $packagefile = &new PEAR_PackageFile($this->config); $pf = &$packagefile->fromTgzFile($file, PEAR_VALIDATE_NORMAL); return $this->_postProcessChecks($pf); }
php
{ "resource": "" }
q266990
PEAR_Common.infoFromDescriptionFile
test
function infoFromDescriptionFile($descfile) { $packagefile = &new PEAR_PackageFile($this->config); $pf = &$packagefile->fromPackageFile($descfile, PEAR_VALIDATE_NORMAL); return $this->_postProcessChecks($pf); }
php
{ "resource": "" }
q266991
PEAR_Common.infoFromString
test
function infoFromString($data) { $packagefile = &new PEAR_PackageFile($this->config); $pf = &$packagefile->fromXmlString($data, PEAR_VALIDATE_NORMAL, false); return $this->_postProcessChecks($pf); }
php
{ "resource": "" }
q266992
PEAR_Common.infoFromAny
test
function infoFromAny($info) { if (is_string($info) && file_exists($info)) { $packagefile = &new PEAR_PackageFile($this->config); $pf = &$packagefile->fromAnyFile($info, PEAR_VALIDATE_NORMAL); if (PEAR::isError($pf)) { $errs = $pf->getUserinfo(); if (is_array($errs)) { foreach ($errs as $error) { $e = $this->raiseError($error['message'], $error['code'], null, null, $error); } } return $pf; } return $this->_postProcessValidPackagexml($pf); } return $info; }
php
{ "resource": "" }
q266993
Articles.getWithOffers
test
public function getWithOffers() { if ((int) $this->id <= 0) { throw new NullPointerException("Id is not set."); } // build url $url = $this->base_url . str_replace("{id}", $this->id, $this->_url_offers); // get data from server $data = $this->getDataFromUrl($url); // parse result set and get data as array $result = $this->parseJsonData($data); return $result; }
php
{ "resource": "" }
q266994
Articles.getAllWithOffers
test
public function getAllWithOffers() { // build url $url = $this->base_url . $this->_url_all_offers; // get data from server $data = $this->getDataFromUrl($url); // parse result set and get data as array $result = $this->parseJsonData($data); return $result; }
php
{ "resource": "" }
q266995
Articles.search
test
public function search() { if (strlen($this->ean) <= 0) { throw new NullPointerException("EAN is not set."); } $params = array( "ean" => $this->ean ); $url = $this->base_url . self::URL_SEARCH . "?" . http_build_query($params); // get data from server $data = $this->getDataFromUrl($url); // parse result set and get data as array $result = $this->parseJsonData($data); return $result; }
php
{ "resource": "" }
q266996
Logger.setFileHandler
test
protected function setFileHandler(string $logFile, int $logLevel = null) { $this->logFile = $logFile; $stream = new StreamHandler($logFile, $logLevel); $this->pushHandler($stream); }
php
{ "resource": "" }
q266997
Logger.setMailHandler
test
protected function setMailHandler(string $emailTo, string $emailSubject, string $emailFrom, int $logLevel) { $mail = new NativeMailerHandler($emailTo, $emailSubject, $emailFrom, $logLevel); $this->pushHandler($mail); }
php
{ "resource": "" }
q266998
Logger.getLogs
test
public function getLogs(int $limit = 0) { if (!file_exists($this->logFile)) { return []; } $lineCount = 0; $fileAsc = file($this->logFile); $file = array_reverse($fileAsc); $arrOutput = []; foreach ($file as $row) { $currentRow = $this->makeLogRow($row); if (!$currentRow) { continue; } $arrOutput[] = $currentRow; $lineCount++; if ($lineCount > $limit && $limit > 0) { break; } } return $arrOutput; }
php
{ "resource": "" }
q266999
Logger.makeLogRow
test
protected function makeLogRow(string $row) { //[2017-07-22 23:06:48] $date = substr($row, 1, 19); if (!Validator::validateDate($date)) { return false; } $fullMsg = substr($row, 22); $arrMsg = explode(":", $fullMsg); $logLevel = $arrMsg[0]; $msg = substr($fullMsg, strpos($fullMsg, ":")+2); $out = [ "date" => $date, "level" => $logLevel, "msg" => $msg, ]; return $out; }
php
{ "resource": "" }