sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function verifyUserCanAccessChannel(Request $request, $channel) { foreach ($this->channels as $pattern => $callback) { $regexp = preg_replace('/\{(.*?)\}/', '(?<$1>[^\.]+)', $pattern); if (preg_match('/^' .$regexp .'$/', $channel, $matches) !== 1) { continue; } $parameters = array_filter($matches, function ($value, $key) { return is_string($key) && ! empty($value); }, ARRAY_FILTER_USE_BOTH); // The first parameter is always the authenticated User instance. array_unshift($parameters, $request->user()); if ($result = $this->callChannelCallback($callback, $parameters)) { return $this->validAuthenticationResponse($request, $result); } } throw new AccessDeniedHttpException; }
Authenticate the incoming request for a given channel. @param \Nova\Http\Request $request @param string $channel @return mixed
entailment
protected function callChannelCallback($callback, $parameters) { if (is_string($callback)) { list($className, $method) = Str::parseCallback($callback, 'join'); $callback = array( $instance = $this->container->make($className), $method ); $reflector = new ReflectionMethod($instance, $method); } else { $reflector = new ReflectionFunction($callback); } return call_user_func_array( $callback, $this->resolveCallDependencies($parameters, $reflector) ); }
Call a channel callback with the dependencies. @param mixed $callback @param array $parameters @return mixed
entailment
public function resolveCallDependencies(array $parameters, ReflectionFunctionAbstract $reflector) { foreach ($reflector->getParameters() as $key => $parameter) { if ($key === 0) { // The first parameter is always the authenticated User instance. continue; } $instance = $this->transformDependency($parameter, $parameters); if (! is_null($instance)) { array_splice($parameters, $key, 0, array($instance)); } } return $parameters; }
Resolve the given method's type-hinted dependencies. @param array $parameters @param \ReflectionFunctionAbstract $reflector @return array
entailment
protected function transformDependency(ReflectionParameter $parameter, $parameters) { if (is_null($class = $parameter->getClass())) { return; } // The parameter references a class. else if (! $class->isSubclassOf(Model::class)) { return $this->container->make($class->name); } $identifier = Arr::first($parameters, function ($parameterKey) use ($parameter) { return $parameterKey === $parameter->name; }); if (! is_null($identifier)) { $instance = $class->newInstance(); return call_user_func(array($instance, 'find'), $identifier); } }
Attempt to transform the given parameter into a class instance. @param \ReflectionParameter $parameter @param string $name @param array $parameters @return mixed
entailment
protected function formatChannels(array $channels) { return array_map(function ($channel) { if ($channel instanceof Channel) { return $channel->getName(); } return $channel; }, $channels); }
Format the channel array into an array of strings. @param array $channels @return array
entailment
public function translate($x, $y) { $this->tx += $x; $this->ty += $y; return $this; }
@param $x @param $y @return $this
entailment
public function scale($x, $y = null) { return $this->multiply(new self($x, 0, 0, $y !== null ? $y : $x, 0, 0)); }
@param $x @param null $y @return $this
entailment
public function rotate($degrees) { $a = deg2rad($degrees); $cosA = cos($a); $sinA = sin($a); return $this->multiply(new self($cosA, $sinA, -$sinA, $cosA, 0, 0)); }
@param $degrees @return $this
entailment
public function skew($x, $y = null) { return $this->multiply(new self( 1, tan(deg2rad($y)), tan(deg2rad($x !== null ? $x : $y)), 1, 0, 0 )); }
@param $x @param null $y @return $this
entailment
public function multiply(TransformationInterface $other) { $this->a = $this->a * $other->getA() + $this->c * $other->getB(); $this->b = $this->b * $other->getA() + $this->d * $other->getB(); $this->c = $this->a * $other->getC() + $this->c * $other->getD(); $this->d = $this->b * $other->getC() + $this->d * $other->getD(); $this->tx = $this->a * $other->getTx() + $this->c * $other->getTy() + $this->tx; $this->ty = $this->b * $other->getTx() + $this->d * $other->getTy() + $this->ty; return $this; }
@param TransformationInterface $other @return $this
entailment
public function transformPoint(PointInterface $point, PointInterface $origin = null) { $x = $point->getX(); $y = $point->getY(); if ($origin) { $x += $origin->getX(); $y += $origin->getY(); } $x = $this->a * $x + $this->c * $y + $this->tx; $y = $this->b * $x + $this->d * $y + $this->ty; if ($origin) { $x -= $origin->getX(); $y -= $origin->getY(); } return new Point($x, $y); }
@param PointInterface $point @param PointInterface $origin @return PointInterface
entailment
public function transformAnchor(AnchorInterface $anchor, PointInterface $origin = null) { return Anchor::fromPoint($this->transformPoint($anchor, $origin), array_map(function (PointInterface $point) use ($origin) { return $this->transformPoint($point, $origin); }, $anchor->getControlPoints())); }
@param AnchorInterface $anchor @param PointInterface $origin @return AnchorInterface
entailment
public function publish($name, $source) { $package = str_replace('_', '-', $name); $destination = $this->publishPath .str_replace('/', DS, "/packages/{$package}"); if (! $this->files->isDirectory($destination)) { $this->files->makeDirectory($destination, 0777, true); } $success = $this->files->copyDirectory($source, $destination); if (! $success) { throw new \RuntimeException("Unable to publish assets."); } return $success; }
Copy all assets from a given path to the publish path. @param string $name @param string $source @return bool @throws \RuntimeException
entailment
public static function createMultiple(?array $photoSizeArray): ?array { if (is_array($photoSizeArray)) { return array_map(function (array $photoSizeData) { return new self($photoSizeData); }, $photoSizeArray); } return null; }
@param array $photoSizeArray @return PhotoSize[]|null
entailment
public function register() { $this->app->bindShared('schedule', function ($app) { return new Schedule($app); }); $this->registerScheduleRunCommand(); $this->registerScheduleFinishCommand(); }
Register the service provider. @return void
entailment
public function match(string $path, string $method = 'GET'): array { // if enable 'matchAll' if ($matchAll = $this->matchAll) { if (\is_string($matchAll) && $matchAll{0} === '/') { $path = $matchAll; } elseif (\is_callable($matchAll)) { return [self::FOUND, $path, [ 'handler' => $matchAll, ]]; } } $path = $this->formatUriPath($path, $this->ignoreLastSlash); $method = strtoupper($method); // find in route caches. if ($this->cacheRoutes && isset($this->cacheRoutes[$path][$method])) { return [self::FOUND, $path, $this->cacheRoutes[$path][$method]]; } // is a static route path if ($this->staticRoutes && ($routeInfo = $this->findInStaticRoutes($path, $method))) { return [self::FOUND, $path, $routeInfo]; } $first = null; $allowedMethods = []; // eg '/article/12' if ($pos = strpos($path, '/', 1)) { $first = substr($path, 1, $pos - 1); } // is a regular dynamic route(the first node is 1th level index key). if ($first && isset($this->regularRoutes[$first])) { $result = $this->findInRegularRoutes($this->regularRoutes[$first], $path, $method); if ($result[0] === self::FOUND) { return $result; } $allowedMethods = $result[1]; } // is a irregular dynamic route if (isset($this->vagueRoutes[$method])) { $result = $this->findInVagueRoutes($this->vagueRoutes[$method], $path, $method); if ($result[0] === self::FOUND) { return $result; } } // For HEAD requests, attempt fallback to GET if ($method === 'HEAD') { if (isset($this->cacheRoutes[$path]['GET'])) { return [self::FOUND, $path, $this->cacheRoutes[$path]['GET']]; } if ($routeInfo = $this->findInStaticRoutes($path, 'GET')) { return [self::FOUND, $path, $routeInfo]; } if ($first && isset($this->regularRoutes[$first])) { $result = $this->findInRegularRoutes($this->regularRoutes[$first], $path, 'GET'); if ($result[0] === self::FOUND) { return $result; } } if (isset($this->vagueRoutes['GET'])) { $result = $this->findInVagueRoutes($this->vagueRoutes['GET'], $path, 'GET'); if ($result[0] === self::FOUND) { return $result; } } } // If nothing else matches, try fallback routes. $router->any('*', 'handler'); if ($this->staticRoutes && ($routeInfo = $this->findInStaticRoutes('/*', $method))) { return [self::FOUND, $path, $routeInfo]; } if ($this->notAllowedAsNotFound) { return [self::NOT_FOUND, $path, null]; } // collect allowed methods from: staticRoutes, vagueRoutes OR return not found. return $this->findAllowedMethods($path, $method, $allowedMethods); }
find the matched route info for the given request uri path @param string $method @param string $path @return array
entailment
public function getHandler(...$params): array { list($path, $method) = $params; // list($path, $info) = $router; return $this->match($path, $method); }
get handler from router @param array ...$params @return array
entailment
public function registerRoutes(array $requestMapping) { foreach ($requestMapping as $className => $mapping) { if (!isset($mapping['prefix'], $mapping['routes'])) { continue; } // controller prefix $controllerPrefix = $mapping['prefix']; $controllerPrefix = $this->getControllerPrefix($controllerPrefix, $className); $routes = $mapping['routes']; // 注册控制器对应的一组路由 $this->registerRoute($className, $routes, $controllerPrefix); } }
自动注册路由 @param array $requestMapping @throws \LogicException @throws \InvalidArgumentException
entailment
private function registerRoute(string $className, array $routes, string $controllerPrefix) { $controllerPrefix = '/' . \trim($controllerPrefix, '/'); // Circular Registration Route foreach ($routes as $route) { if (!isset($route['route'], $route['method'], $route['action'])) { continue; } $mapRoute = $route['route']; $method = $route['method']; $action = $route['action']; // 解析注入action名称 $mapRoute = empty($mapRoute) ? $action : $mapRoute; // '/'开头的路由是一个单独的路由 未使用'/'需要和控制器组拼成一个路由 $uri = $mapRoute[0] === '/' ? $mapRoute : $controllerPrefix . '/' . $mapRoute; $handler = $className . '@' . $action; // 注入路由规则 $this->map($method, $uri, $handler, [ 'params' => $route['params'] ?? [] ]); } }
注册路由 @param string $className 类名 @param array $routes 控制器对应的路由组 @param string $controllerPrefix 控制器prefix @throws \LogicException @throws \InvalidArgumentException
entailment
private function getControllerPrefix(string $controllerPrefix, string $className): string { // 注解注入不为空,直接返回prefix if (!empty($controllerPrefix)) { return $controllerPrefix; } // 注解注入为空,解析控制器prefix $reg = '/^.*\\\(\w+)' . $this->controllerSuffix . '$/'; $prefix = ''; if ($result = \preg_match($reg, $className, $match)) { $prefix = '/' . \lcfirst($match[1]); } return $prefix; }
获取控制器prefix @param string $controllerPrefix 注解控制器prefix @param string $className 控制器类名 @return string
entailment
public function register() { $this->app['events'] = $this->app->share(function($app) { return with(new Dispatcher($app))->setQueueResolver(function () use ($app) { return $app['queue']; }); }); }
Register the service provider. @return void
entailment
public static function make(array $items, $total, $perPage = 15, $pageName = 'page', $page = null) { if (is_null($page)) { $page = static::resolveCurrentPage($pageName); } $path = static::resolveCurrentPath($pageName); return new static($items, $total, $perPage, $page, compact('path', 'pageName')); }
Create and return a new Paginator instance. @param int $page @return bool
entailment
public function render($view = null, $data = array()) { if (is_null($view)) { $view = static::$defaultView; } $data = array_merge($data, array( 'paginator' => $this, 'elements' => $this->elements(), )); return new HtmlString( static::viewFactory()->make($view, $data)->render() ); }
Render the paginator using the given view. @param string $view @param array $data @return string
entailment
protected function elements() { $window = $this->getUrlWindow($this->onEachSide); return array_filter(array( $window['first'], is_array($window['slider']) ? '...' : null, $window['slider'], is_array($window['last']) ? '...' : null, $window['last'], )); }
Get the array of elements to pass to the view. @return array
entailment
public function getUrlWindow($onEachSide = 3) { if (! $this->hasPages()) { return array('first' => null, 'slider' => null, 'last' => null); } $window = $onEachSide * 2; if ($this->lastPage() < ($window + 6)) { return $this->getSmallSlider(); } // If the current page is very close to the beginning of the page range, we will // just render the beginning of the page range, followed by the last 2 of the // links in this list, since we will not have room to create a full slider. if ($this->currentPage() <= $window) { return $this->getSliderTooCloseToBeginning($window); } // If the current page is close to the ending of the page range we will just get // this first couple pages, followed by a larger window of these ending pages // since we're too close to the end of the list to create a full on slider. else if ($this->currentPage() > ($this->lastPage() - $window)) { return $this->getSliderTooCloseToEnding($window); } // If we have enough room on both sides of the current page to build a slider we // will surround it with both the beginning and ending caps, with this window // of pages in the middle providing a Google style sliding paginator setup. return $this->getFullSlider($onEachSide); }
Get the window of URLs to be shown. @param int $onEachSide @return array
entailment
protected function getSliderTooCloseToBeginning($window) { $lastPage = $this->lastPage(); return array( 'first' => $this->getUrlRange(1, $window + 2), 'slider' => null, 'last' => $this->getUrlRange($lastPage - 1, $lastPage), ); }
Get the slider of URLs when too close to beginning of window. @param int $window @return array
entailment
protected function getSliderTooCloseToEnding($window) { $lastPage = $this->lastPage(); $last = $this->getUrlRange($lastPage - ($window + 2), $lastPage); return array( 'first' => $this->getUrlRange(1, 2), 'slider' => null, 'last' => $last, ); }
Get the slider of URLs when too close to ending of window. @param int $window @return array
entailment
protected function getFullSlider($onEachSide) { $currentPage = $this->currentPage(); $slider = $this->getUrlRange( $currentPage - $onEachSide, $currentPage + $onEachSide ); $lastPage = $this->lastPage(); return array( 'first' => $this->getUrlRange(1, 2), 'slider' => $slider, 'last' => $this->getUrlRange($lastPage - 1, $lastPage), ); }
Get the slider of URLs when a full slider can be made. @param int $onEachSide @return array
entailment
protected function pushForeverKeys($namespace, $key) { $fullKey = $this->getPrefix().sha1($namespace).':'.$key; foreach (explode('|', $namespace) as $segment) { $this->store->connection()->lpush($this->foreverKey($segment), $fullKey); } }
Store a copy of the full key for each namespace segment. @param string $namespace @param string $key @return void
entailment
protected function deleteForeverKeys() { foreach (explode('|', $this->tags->getNamespace()) as $segment) { $this->deleteForeverValues($segment = $this->foreverKey($segment)); $this->store->connection()->del($segment); } }
Delete all of the items that were stored forever. @return void
entailment
protected function deleteForeverValues($foreverKey) { $forever = array_unique($this->store->connection()->lrange($foreverKey, 0, -1)); if (count($forever) > 0) { call_user_func_array(array($this->store->connection(), 'del'), $forever); } }
Delete all of the keys that have been stored forever. @param string $foreverKey @return void
entailment
protected function getNamespaceName($className = null) { $parts = explode('\\', $className ?: $this->className); array_pop($parts); return implode('\\', $parts); }
Get the namespace for the mocked class. @param string $className @return string
entailment
protected function getClassName($className = null) { $parts = explode('\\', $className ?: $this->className); return $parts[count($parts) - 1]; }
Get the class name (not including the namespace) of the class to be mocked. @param string $className @return string
entailment
public function generateCode() { $refClass = new ReflectionClass($this->className); $this->finalClassesCanNotBeMocked($refClass); $this->methods = array(); $this->makeAllAbstractMethodsThrowException($refClass); if (!$this->niceMock || $refClass->isInterface()) { $this->makeAllMethodsThrowException($refClass); } $this->renderRules(); $this->renderConstructor(); $this->renderClone(); $this->exposeMethods(); $this->setUpGetCallsForMethod(); $code = $this->getNamespaceCode(); $methods = implode("\n", $this->methods); $superWord = $this->getSuperWord($refClass); $class = "class {$this->getMockName()} $superWord \\{$this->className}"; if ('implements' === $superWord) { $class .= ', '; } else { $class .= ' implements '; } $class .= '\Concise\Mock\MockInterface'; return $code . "$class { public static \$_methodCalls = array(); $methods }"; }
Generate the PHP code for the mocked class. @return string
entailment
protected function getMockName() { if ($this->customClassName) { return $this->getClassName($this->customClassName); } return $this->getClassName() . $this->mockUnique; }
Get the name of the mocked class (not including the namespace). @return string
entailment
public function newInstance() { /** @noinspection PhpUnusedLocalVariableInspection */ $name = "{$this->getMockNamespaceName()}\\{$this->getMockName()}"; /** @noinspection PhpUnusedLocalVariableInspection */ $code = $this->generateCode(); /** @var $reflect \ReflectionClass */ $reflect = eval("$code return new \\ReflectionClass('$name');"); try { return $reflect->newInstanceArgs($this->constructorArgs); } catch (ReflectionException $e) { return $reflect->newInstance(); } }
Create a new instance of the mocked class. There is no need to generate the code before invoking this. @return object
entailment
public function push($filename, LoggerInterface $logger) { $this->doRotate(Backup::fromFile($filename), $logger); return $this->destination->push($filename, $logger); }
{@inheritdoc}
entailment
public function instance($domain = 'app', $locale = null) { $locale = $locale ?: $this->locale; // The ID code is something like: 'en/system', 'en/app' or 'en/file_manager' $id = $locale .'/' .$domain; // Returns the Language domain instance, if it already exists. if (isset($this->instances[$id])) return $this->instances[$id]; return $this->instances[$id] = new Language($this, $domain, $locale); }
Get instance of Language with domain and code (optional). @param string $domain Optional custom domain @param string $code Optional custom language code. @return Language
entailment
public function package($package, $hint, $namespace = null) { $namespace = $this->getPackageNamespace($package, $namespace); $this->addNamespace($namespace, $hint); }
Register a Package for cascading configuration. @param string $package @param string $hint @param string $namespace @return void
entailment
public function setLocale($locale) { // Setup the Framework locale. $this->locale = $locale; // Retrieve the full locale from languages list. $language = array_get($this->languages, $locale .'.locale', 'en_US') .'.utf8'; // Setup the Carbon and PHP's time locale. setlocale(LC_TIME, $language); Carbon::setLocale($locale); }
Set the default locale. @param string $locale @return void
entailment
public static function getTableName() { $r = new \ReflectionClass(static::class); $classNameUpperCamelCase = $r->getShortName(); $classNameLower = strtolower($classNameUpperCamelCase); return $classNameLower . 's'; }
return name of MySQL table based on the class name e.g. if class is: Itb\Dvd then return dvds i.e. lower case with 's' on the end @return string
entailment
public static function delete($id) { $db = new DatabaseManager(); $connection = $db->getDbh(); $statement = $connection->prepare('DELETE from ' . static::getTableName() . ' WHERE id=:id'); $statement->bindParam(':id', $id, \PDO::PARAM_INT); $queryWasSuccessful = $statement->execute(); return $queryWasSuccessful; }
delete record for given ID - return true/false depending on delete success @param $id @return bool
entailment
public static function insert($object) { $db = new DatabaseManager(); $connection = $db->getDbh(); $objectAsArrayForSqlInsert = DatatbaseUtility::objectToArrayLessId($object); $fields = array_keys($objectAsArrayForSqlInsert); $insertFieldList = DatatbaseUtility::fieldListToInsertString($fields); $valuesFieldList = DatatbaseUtility::fieldListToValuesString($fields); $statement = $connection->prepare('INSERT into '. static::getTableName() . ' ' . $insertFieldList . $valuesFieldList); $statement->execute($objectAsArrayForSqlInsert); $queryWasSuccessful = ($statement->rowCount() > 0); if ($queryWasSuccessful) { return $connection->lastInsertId(); } else { return -1; } }
insert new record into the DB table returns new record ID if insertation was successful, otherwise -1 @param Object $object @return integer
entailment
public static function update(DatabaseTable $object) { $db = new DatabaseManager(); $connection = $db->getDbh(); $objectAsArrayForSqlInsert = DatatbaseUtility::objectToArrayLessId($object); $fields = array_keys($objectAsArrayForSqlInsert); $updateFieldList = DatatbaseUtility::fieldListToUpdateString($fields); $sql = 'UPDATE '. static::getTableName() . ' SET ' . $updateFieldList . ' WHERE id=:id'; $statement = $connection->prepare($sql); // add 'id' to parameters array $objectAsArrayForSqlInsert['id'] = $object->getId(); $queryWasSuccessful = $statement->execute($objectAsArrayForSqlInsert); return $queryWasSuccessful; }
insert new record into the DB table returns new record ID if insertion was successful, otherwise -1 @param Object $object @return integer
entailment
public function publishPackage($package) { $source = $this->getSource($package); return $this->publish($package, $source); }
Publish the configuration files for a package. @param string $package @param string $packagePath @return bool
entailment
protected function getSource($package) { $namespaces = $this->config->getNamespaces(); $source = isset($namespaces[$package]) ? $namespaces[$package] : null; if (is_null($source) || ! $this->files->isDirectory($source)) { throw new \InvalidArgumentException("Configuration not found."); } return $source; }
Get the source configuration directory to publish. @param string $package @return string @throws \InvalidArgumentException
entailment
protected function makeDestination($destination) { if ( ! $this->files->isDirectory($destination)) { $this->files->makeDirectory($destination, 0777, true); } }
Create the destination directory if it doesn't exist. @param string $destination @return void
entailment
public function alreadyPublished($package) { $path = $this->getDestinationPath($package); return $this->files->isDirectory($path); }
Determine if a given package has already been published. @param string $package @return bool
entailment
public function getDestinationPath($package) { $packages = $this->config->getPackages(); $namespace = isset($packages[$package]) ? $packages[$package] : null; if (is_null($namespace)) { throw new \InvalidArgumentException("Configuration not found."); } return $this->publishPath .str_replace('/', DS, "/Packages/{$namespace}"); }
Get the target destination path for the configuration files. @param string $package @return string
entailment
public function handle() { if (! $this->confirmToProceed()) { return; } $this->resolver->setDefaultConnection($this->getDatabase()); $this->getSeeder()->run(); }
Execute the console command. @return void
entailment
protected function getSeeder() { $className = str_replace('/', '\\', $this->input->getOption('class')); $rootNamespace = $this->container->getNamespace(); if (! Str::startsWith($className, $rootNamespace) && ! Str::contains($className, '\\')) { $className = $rootNamespace .'Database\Seeds\\' .$className; } $instance = $this->container->make($className); return $instance->setContainer($this->container)->setCommand($this); }
Get a seeder instance from the container. @return \Nova\Database\Seeder
entailment
public function setRequestLocation(bool $requestLocation = null): self { $this->requestLocation = $requestLocation; if ($requestLocation === true) { $this->requestContact = null; } return $this; }
@param bool|null $requestLocation @return KeyboardButton
entailment
public function setRequestContact(bool $requestContact = null): self { $this->requestContact = $requestContact; if ($requestContact === true) { $this->requestLocation = null; } return $this; }
@param bool|null $requestContact @return KeyboardButton
entailment
function jsonSerialize() { $result = [ 'text' => $this->text ]; if ($this->requestContact !== null) { $result['request_contact'] = $this->requestContact; } if ($this->requestLocation !== null) { $result['request_location'] = $this->requestLocation; } return $result; }
Specify data which should be serialized to JSON
entailment
public function getSortedQuestions() { $criteria = Criteria::create(); $criteria->orderBy(array('rank' => 'ASC')); return $this->getQuestions()->matching($criteria); }
Get Sorted questions by Rank @return \Doctrine\Common\Collections\Collection
entailment
protected function runSoftDelete() { $query = $this->newQuery()->where($this->getKeyName(), $this->getKey()); $this->setAttribute($column = $this->getDeletedAtColumn(), $time = $this->freshTimestamp()); $query->update(array($column => $this->fromDateTime($time))); }
Perform the actual delete query on this model instance. @return void
entailment
public static function onlyTrashed() { $instance = new static; $column = $instance->getQualifiedDeletedAtColumn(); return $instance->newQueryWithoutScope(new SoftDeletingScope)->whereNotNull($column); }
Get a new query builder that only includes soft deletes. @return \Nova\Database\ORM\Builder|static
entailment
public function handle($passable, Closure $callback) { $pipeline = array_reduce(array_reverse($this->pipes), function ($stack, $pipe) { return $this->createSlice($stack, $pipe); }, $this->prepareDestination($callback)); return call_user_func($pipeline, $passable); }
Run the pipeline with a final destination callback. @param mixed $passable @param \Closure $callback @return mixed
entailment
protected function createSlice($stack, $pipe) { return function ($passable) use ($stack, $pipe) { return $this->call($pipe, $passable, $stack); }; }
Get a Closure that represents a slice of the application onion. @return \Closure
entailment
protected function call($pipe, $passable, $stack) { if ($pipe instanceof Closure) { return call_user_func($pipe, $passable, $stack); } // The pipe is not a Closure instance. else if (! is_object($pipe)) { list($name, $parameters) = $this->parsePipeString($pipe); $pipe = $this->getContainer()->make($name); $parameters = array_merge(array($passable, $stack), $parameters); } else { $parameters = array($passable, $stack); } return call_user_func_array(array($pipe, $this->method), $parameters); }
Call the pipe Closure or the method 'handle' in its class instance. @param mixed $pipe @param mixed $passable @param \Closure $stack @return \Closure @throws \BadMethodCallException
entailment
protected function parsePipeString($pipe) { list($name, $parameters) = array_pad(explode(':', $pipe, 2), 2, array()); if (is_string($parameters)) { $parameters = explode(',', $parameters); } return array($name, $parameters); }
Parse full pipe string to get name and parameters. @param string $pipe @return array
entailment
public function addRequestHeader($name, $value, $override = true) { return $this->addHeaderRequest($name, $value, $override); }
Adiciona um campo de cabeçalho para ser enviado com a requisição. @param string $name Nome do campo de cabeçalho. @param string $value Valor do campo de cabeçalho. @param bool $override Indica se o campo deverá ser sobrescrito caso já tenha sido definido. @return bool @throws \InvalidArgumentException Se o nome ou o valor do campo não forem valores scalar. @see \Moip\Http\HTTPRequest::addRequestHeader()
entailment
public function connect(array $config) { $pheanstalk = new Pheanstalk($config['host'], array_get($config, 'port', PheanstalkInterface::DEFAULT_PORT)); return new BeanstalkdQueue( $pheanstalk, $config['queue'], array_get($config, 'ttr', Pheanstalk::DEFAULT_TTR) ); }
Establish a queue connection. @param array $config @return \Nova\Queue\Contracts\QueueInterface
entailment
public function handle() { $user = User::where('email',$this->argument('email'))->firstOrFail(); $role = Role::whereSlug($this->argument('rank'))->firstOrFail(); $user->update([config('artify.permissions_column') => null]); $user->roles()->sync($role); return $this->info("$user->email Role is set to `{$role->slug}`"); }
Execute the console command. @return mixed
entailment
protected static function resolveFacadeInstance($name) { if (is_object($name)) return $name; if (isset(static::$resolvedInstance[$name])) { return static::$resolvedInstance[$name]; } return static::$resolvedInstance[$name] = static::$app[$name]; }
Resolve the facade root instance from the container. @param string $name @return mixed
entailment
public function containsString() { if (strpos($this->data[0], $this->data[1]) === false) { throw new DidNotMatchException(); } return $this->data[0]; }
A string contains a substring. Returns original string. @return mixed @throws DidNotMatchException @syntax string ?:string contains ?:string
entailment
public function containsStringIgnoringCase() { $this->data = array( strtolower($this->data[0]), strtolower($this->data[1]) ); return $this->containsString(); }
A string contains a substring (ignoring case-sensitivity). Returns original string. @return mixed @syntax string ?:string contains case insensitive ?:string
entailment
public function doesNotContainString() { if (strpos($this->data[0], $this->data[1]) !== false) { throw new DidNotMatchException(); } return $this->data[0]; }
A string does not contain a substring. Returns original string. @return mixed @throws DidNotMatchException @syntax string ?:string does not contain ?:string
entailment
public function doesNotContainStringIgnoringCase() { $this->data = array( strtolower($this->data[0]), strtolower($this->data[1]) ); return $this->doesNotContainString(); }
A string does not contain a substring (ignoring case-sensitivity). Returns original string. @return mixed @syntax string ?:string does not contain case insensitive ?:string
entailment
protected function requireMigrations($package) { $files = $this->container['files']; // $path = $this->getMigrationPath($package); $migrations = $files->glob($path.'*_*.php'); foreach ($migrations as $migration) { $files->requireOnce($migration); } }
Require (once) all migration files for the supplied Package. @param string $package
entailment
public function get() { $compiler = new ClassCompiler( $this->className, $this->niceMock, $this->constructorArgs, $this->disableConstructor, $this->disableClone ); if ($this->customClassName) { $compiler->setCustomClassName($this->customClassName); } $compiler->setRules($this->rules); foreach ($this->expose as $method) { $compiler->addExpose($method); } $mockInstance = $compiler->newInstance(); $this->testCase->addMockInstance($this, $mockInstance); $this->restoreState($mockInstance); foreach ($this->properties as $name => $value) { $this->testCase->setProperty($mockInstance, $name, $value); } return $mockInstance; }
Compiler the mock into a usable instance. @return object
entailment
public function with() { $methodArguments = new MethodArguments(); $this->currentWith = $methodArguments->getMethodArgumentValues( func_get_args(), $this->getClassName() . "::" . $this->currentRules[0] ); foreach ($this->currentRules as $rule) { if ($this->rules[$rule][md5('null')]['hasSetTimes']) { $renderer = new ValueRenderer(); $converter = new NumberToTimesConverter(); $args = $renderer->renderAll($this->currentWith); $times = $this->rules[$rule][md5('null')]['times']; $convertToMethod = $converter->convertToMethod($times); throw new Exception( sprintf( "%s:\n ->expects('%s')->with(%s)->%s", "When using with you must specify expectations for each with()", $rule, $args, $convertToMethod ) ); } $this->rules[$rule][md5('null')]['times'] = -1; } $this->setupWith( new Action\ReturnValueAction(array(null)), $this->isExpecting ? 1 : -1 ); return $this; }
Expected arguments when invoking the mock. @throws \Exception @return MockBuilder
entailment
public function handle($request, Closure $next) { $contentLength = $request->server('CONTENT_LENGTH'); if ($contentLength > $this->getPostMaxSize()) { throw new PostTooLargeException(); } return $next($request); }
Handle an incoming request. @param \Nova\Http\Request $request @param \Closure $next @return mixed @throws \Nova\Http\Exception\PostTooLargeException
entailment
protected function getPostMaxSize() { $postMaxSize = ini_get('post_max_size'); switch (substr($postMaxSize, -1)) { case 'M': case 'm': return (int) $postMaxSize * 1048576; case 'K': case 'k': return (int) $postMaxSize * 1024; case 'G': case 'g': return (int) $postMaxSize * 1073741824; } return (int) $postMaxSize; }
Determine the server 'post_max_size' as bytes. @return int
entailment
public function withInput(array $input = null) { $input = $input ?: $this->request->input(); $this->session->flashInput(array_filter($input, function ($value) { return ! $value instanceof SymfonyUploadedFile; })); return $this; }
Flash an array of input to the session. @param array $input @return $this
entailment
public function withErrors($provider, $key = 'default') { $value = $this->parseErrors($provider); $this->session->flash( 'errors', $this->session->get('errors', new ViewErrorBag)->put($key, $value) ); return $this; }
Flash a container of errors to the session. @param \Nova\Support\Contracts\MessageProviderInterface|array $provider @param string $key @return $this
entailment
protected function parseErrors($provider) { if ($provider instanceof MessageBag) { return $provider; } else if ($provider instanceof MessageProviderInterface) { return $provider->getMessageBag(); } return new MessageBag((array) $provider); }
Parse the given errors into an appropriate value. @param \Nova\Support\Contracts\MessageProviderInterface|array $provider @return \Nova\Support\MessageBag
entailment
public function fullUrl() { $query = $this->getQueryString(); return $query ? $this->url().'?'.$query : $this->url(); }
Get the full URL for the request. @return string
entailment
protected function isEmptyString($key) { $boolOrArray = is_bool($this->input($key)) || is_array($this->input($key)); return ! $boolOrArray && (trim((string) $this->input($key)) === ''); }
Determine if the given input key is an empty string for "has". @param string $key @return bool
entailment
public function input($key = null, $default = null) { $input = $this->getInputSource()->all() + $this->query->all(); return array_get($input, $key, $default); }
Retrieve an input item from the request. @param string $key @param mixed $default @return string
entailment
public function except($keys) { $keys = is_array($keys) ? $keys : func_get_args(); $results = $this->all(); array_forget($results, $keys); return $results; }
Get all of the input except for a specified array of items. @param array $keys @return array
entailment
public function flashOnly($keys) { $keys = is_array($keys) ? $keys : func_get_args(); return $this->flash('only', $keys); }
Flash only some of the input to the session. @param mixed string @return void
entailment
public function flashExcept($keys) { $keys = is_array($keys) ? $keys : func_get_args(); return $this->flash('except', $keys); }
Flash only some of the input to the session. @param mixed string @return void
entailment
public static function createFromBase(SymfonyRequest $request) { if ($request instanceof static) return $request; $content = $request->content; $request = (new static)->duplicate( $request->query->all(), $request->request->all(), $request->attributes->all(), $request->cookies->all(), $request->files->all(), $request->server->all() ); $request->content = $content; $request->request = $request->getInputSource(); return $request; }
Create an Nova request from a Symfony instance. @param \Symfony\Component\HttpFoundation\Request $request @return \Nova\Http\Request
entailment
public function route($param = null) { $route = call_user_func($this->getRouteResolver()); if (is_null($route) || is_null($param)) { return $route; } else { return $route->parameter($param); } }
Get the route handling the request. @param string|null $param @return \Nova\Routing\Route|object|string
entailment
public function fingerprint() { if (is_null($route = $this->route())) { throw new RuntimeException('Unable to generate fingerprint. Route unavailable.'); } return sha1(implode('|', array_merge( $route->methods(), array($route->domain(), $route->uri(), $this->ip()) ))); }
Get a unique fingerprint for the request / route / IP address. @return string @throws \RuntimeException
entailment
public function register() { $this->setupDefaultDriver(); $this->registerSessionManager(); $this->registerSessionDriver(); // $this->app->singleton('Nova\Session\Middleware\StartSession'); }
Register the service provider. @return void
entailment
protected function callCustomCreator($name, array $config) { $driver = $config['driver']; $callback = $this->customCreators[$driver]; return call_user_func($callback, $this->app, $name, $config); }
Call a custom driver creator. @param string $name @param array $config @return mixed
entailment
public function createUserProvider($provider) { $config = $this->app['config']["auth.providers.{$provider}"]; // Retrieve the driver from configuration. $driver = $config['driver']; if (isset($this->customProviderCreators[$driver])) { $callback = $this->customProviderCreators[$driver]; return call_user_func($callback, $this->app, $config); } switch ($driver) { case 'database': return $this->createDatabaseProvider($config); case 'extended': return $this->createExtendedProvider($config); default: break; } throw new InvalidArgumentException("Authentication user provider [{$driver}] is not defined."); }
Create the user provider implementation for the driver. @param string $provider @return \Nova\Auth\UserProviderInterface @throws \InvalidArgumentException
entailment
public function shouldUse($name) { $this->setDefaultDriver($name); $this->userResolver = function ($name = null) { return $this->guard($name)->user(); }; }
Set the default guard driver the factory should serve. @param string $name @return void
entailment
public function register() { $this->app->bindShared('composer', function($app) { return new Composer($app['files'], $app['path.base']); }); $this->app->bindShared('forge', function($app) { return new Forge($app); }); // Register the additional service providers. $this->app->register('Nova\Console\ScheduleServiceProvider'); $this->app->register('Nova\Queue\ConsoleServiceProvider'); }
Register the Service Provider. @return void
entailment
public function DumpList($options = array(), $listId = false) { $api = $this->url . 'list/'; if (!$listId) $listId = $this->listId; $payload = array_merge(array('id' => $this->listId), $options); $data = $this->requestMonkey($api, $payload, true); if (empty($data) || !isset($data)) return $data; $result = preg_split('/$\R?^/m', $data); $headerArray = json_decode($result[0]); unset($result[0]); $data = array(); foreach ($result as $value) { $data[] = array_combine($headerArray, json_decode($value)); } return $data; }
Dump members of a list @link http://apidocs.mailchimp.com/export/1.0/list.func.php Read mailchimp api docs @param array $options @param string $listId @return array
entailment
public function campaignSubscriberActivity($id, $options = array()) { $api = $api = $this->url . 'campaignSubscriberActivity/'; $payload = array_merge(array('id' => $id), $options); $data = $this->requestMonkey($api, $payload, true); // If json_decode doesn't seem to work when there are separated objects if ($jData = json_decode($data,true)) { return $jData; } // We combine them into one object $data = preg_replace('/(}\s{)/',',',$data); return json_decode($data,true); }
Exports/dumps all Subscriber Activity for the requested campaign @link http://apidocs.mailchimp.com/export/1.0/campaignsubscriberactivity.func.php campaignSubscriberActivity method @param int $id @param array $options @return array
entailment
protected function replaceUserNamespace($stub) { $config = $this->container['config']; // $namespaceModel = $config->get('auth.providers.users.model', 'App\Models\User'); $model = class_basename(trim($namespaceModel, '\\')); // $stub = str_replace('{{fullUserModel}}', $namespaceModel, $stub); return str_replace('{{userModel}}', $model, $stub); }
Replace the User model namespace. @param string $stub @return string
entailment
protected function replaceModel($stub, $model) { $model = str_replace('/', '\\', $model); $namespaceModel = $this->container->getNamespace() .'Models\\' .$model; if (Str::startsWith($model, '\\')) { $stub = str_replace('{{fullModel}}', trim($model, '\\'), $stub); } else { $stub = str_replace('{{fullModel}}', $namespaceModel, $stub); } $stub = str_replace( "use {$namespaceModel};\nuse {$namespaceModel};", "use {$namespaceModel};", $stub ); $model = class_basename(trim($model, '\\')); $stub = str_replace('{{model}}', $model, $stub); $stub = str_replace('{{camelModel}}', Str::camel($model), $stub); return str_replace('{{pluralModel}}', Str::plural(Str::camel($model)), $stub); }
Replace the model for the given stub. @param string $stub @param string $model @return string
entailment
protected function getStub() { if ($this->option('model')) { return realpath(__DIR__) .str_replace('/', DS, '/stubs/policy.stub'); } else { return realpath(__DIR__) .str_replace('/', DS, '/stubs/policy.plain.stub'); } }
Get the stub file for the generator. @return string
entailment
public function handle() { $this->domain = ucfirst($this->argument('domain')); $this->name = ucfirst($this->argument('name')); $this->setFiles(); foreach ($this->files as $filename) { if (in_array($filename, $this->requiresDomain)) { $customName = str_singular($this->domain); $this->hasOrCreateDirectory($this->domain . '/Domain/' . str_plural(explode('.', $filename)[0])); } else { $this->hasOrCreateDirectory($this->domain . '/' . str_plural(explode('.', $filename)[0])); $customName = null; } if ($originalContent = $this->hasOrFetchDummyFile($filename)) { if ($filename == 'Model.stub') { $this->call('make:model', [ 'name' => $this->domain . '\\Domain\\Models\\' . $customName, '--migration' => true, '--factory' => true, ]); $this->call('make:observer', [ 'name' => 'App\\' . $this->domain . '\\Domain\\Observers\\' . $customName . 'Observer', '--model' => $this->domain . '\\Domain\\Models\\' . $customName, ]); $this->call('artify:repository', [ 'name' => 'App\\' . $this->domain . '\\Domain\\Repositories\\' . $customName . 'Repository' ]); } else { if ($filename == 'Service.stub') { $fileContent = str_replace(['DummyDomain', 'DummyName', 'Dummy', 'dummies', 'dummy'], [$this->domain, $this->name, str_singular($this->domain), strtolower($this->domain), strtolower(str_singular($this->domain))], $originalContent); } else { $fileContent = str_replace(['DummyDomain', 'Dummy', 'dummies', 'dummy'], [$this->domain, $customName ?? $this->name, strtolower(str_plural($customName ?? $this->name)), strtolower($customName ?? $this->name)], $originalContent); } $this->filesystem->put(__DIR__ . '/stubs/adr/' . $filename, $fileContent); $this->filesystem->copy(__DIR__ . '/stubs/adr/' . $filename, $this->getMovingFilePath($filename)); $this->filesystem->put(__DIR__ . '/stubs/adr/' . $filename, $originalContent); } } } }
Execute the console command. @return mixed
entailment
public function connect(array $config) { $dsn = $this->getDsn($config); $options = $this->getOptions($config); $connection = $this->createConnection($dsn, $config, $options); // $collation = $config['collation']; $charset = $config['charset']; $names = "set names '$charset'". (! is_null($collation) ? " collate '$collation'" : ''); $connection->prepare($names)->execute(); if (isset($config['strict']) && $config['strict']) { $connection->prepare("set session sql_mode='STRICT_ALL_TABLES'")->execute(); } return $connection; }
Establish a database connection. @param array $config @return \PDO
entailment
protected function getDsn(array $config) { extract($config); $dsn = "mysql:host={$hostname};dbname={$database}"; if (isset($config['port'])) { $dsn .= ";port={$port}"; } if (isset($config['unix_socket'])) { $dsn .= ";unix_socket={$config['unix_socket']}"; } return $dsn; }
Create a DSN string from a configuration. @param array $config @return string
entailment
public function hashName($path = null) { if (! is_null($path)) { $path = rtrim($path, '/\\') .DS; } return $path .md5_file($this->path()) .'.' .$this->extension(); }
Get a filename for the file that is the MD5 hash of the contents. @param string $path @return string
entailment