id
int32
0
241k
repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
37,600
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.incrementDislikesCount
public function incrementDislikesCount(LikeableContract $likeable) { $counter = $likeable->dislikesCounter()->first(); if (!$counter) { $counter = $likeable->dislikesCounter()->create([ 'count' => 0, 'type_id' => LikeType::DISLIKE, ]); } $counter->increment('count'); }
php
public function incrementDislikesCount(LikeableContract $likeable) { $counter = $likeable->dislikesCounter()->first(); if (!$counter) { $counter = $likeable->dislikesCounter()->create([ 'count' => 0, 'type_id' => LikeType::DISLIKE, ]); } $counter->increment('count'); }
[ "public", "function", "incrementDislikesCount", "(", "LikeableContract", "$", "likeable", ")", "{", "$", "counter", "=", "$", "likeable", "->", "dislikesCounter", "(", ")", "->", "first", "(", ")", ";", "if", "(", "!", "$", "counter", ")", "{", "$", "counter", "=", "$", "likeable", "->", "dislikesCounter", "(", ")", "->", "create", "(", "[", "'count'", "=>", "0", ",", "'type_id'", "=>", "LikeType", "::", "DISLIKE", ",", "]", ")", ";", "}", "$", "counter", "->", "increment", "(", "'count'", ")", ";", "}" ]
Increment the total dislike count stored in the counter. @param \Cog\Likeable\Contracts\Likeable $likeable @return void
[ "Increment", "the", "total", "dislike", "count", "stored", "in", "the", "counter", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L217-L229
37,601
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.removeLikeCountersOfType
public function removeLikeCountersOfType($likeableType, $type = null) { if (class_exists($likeableType)) { /** @var \Cog\Likeable\Contracts\Likeable $likeable */ $likeable = new $likeableType; $likeableType = $likeable->getMorphClass(); } /** @var \Illuminate\Database\Eloquent\Builder $counters */ $counters = app(LikeCounterContract::class)->where('likeable_type', $likeableType); if (!is_null($type)) { $counters->where('type_id', $this->getLikeTypeId($type)); } $counters->delete(); }
php
public function removeLikeCountersOfType($likeableType, $type = null) { if (class_exists($likeableType)) { /** @var \Cog\Likeable\Contracts\Likeable $likeable */ $likeable = new $likeableType; $likeableType = $likeable->getMorphClass(); } /** @var \Illuminate\Database\Eloquent\Builder $counters */ $counters = app(LikeCounterContract::class)->where('likeable_type', $likeableType); if (!is_null($type)) { $counters->where('type_id', $this->getLikeTypeId($type)); } $counters->delete(); }
[ "public", "function", "removeLikeCountersOfType", "(", "$", "likeableType", ",", "$", "type", "=", "null", ")", "{", "if", "(", "class_exists", "(", "$", "likeableType", ")", ")", "{", "/** @var \\Cog\\Likeable\\Contracts\\Likeable $likeable */", "$", "likeable", "=", "new", "$", "likeableType", ";", "$", "likeableType", "=", "$", "likeable", "->", "getMorphClass", "(", ")", ";", "}", "/** @var \\Illuminate\\Database\\Eloquent\\Builder $counters */", "$", "counters", "=", "app", "(", "LikeCounterContract", "::", "class", ")", "->", "where", "(", "'likeable_type'", ",", "$", "likeableType", ")", ";", "if", "(", "!", "is_null", "(", "$", "type", ")", ")", "{", "$", "counters", "->", "where", "(", "'type_id'", ",", "$", "this", "->", "getLikeTypeId", "(", "$", "type", ")", ")", ";", "}", "$", "counters", "->", "delete", "(", ")", ";", "}" ]
Remove like counters by likeable type. @param string $likeableType @param string|null $type @return void @throws \Cog\Likeable\Exceptions\LikeTypeInvalidException
[ "Remove", "like", "counters", "by", "likeable", "type", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L240-L254
37,602
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.removeModelLikes
public function removeModelLikes(LikeableContract $likeable, $type) { app(LikeContract::class)->where([ 'likeable_id' => $likeable->getKey(), 'likeable_type' => $likeable->getMorphClass(), 'type_id' => $this->getLikeTypeId($type), ])->delete(); app(LikeCounterContract::class)->where([ 'likeable_id' => $likeable->getKey(), 'likeable_type' => $likeable->getMorphClass(), 'type_id' => $this->getLikeTypeId($type), ])->delete(); }
php
public function removeModelLikes(LikeableContract $likeable, $type) { app(LikeContract::class)->where([ 'likeable_id' => $likeable->getKey(), 'likeable_type' => $likeable->getMorphClass(), 'type_id' => $this->getLikeTypeId($type), ])->delete(); app(LikeCounterContract::class)->where([ 'likeable_id' => $likeable->getKey(), 'likeable_type' => $likeable->getMorphClass(), 'type_id' => $this->getLikeTypeId($type), ])->delete(); }
[ "public", "function", "removeModelLikes", "(", "LikeableContract", "$", "likeable", ",", "$", "type", ")", "{", "app", "(", "LikeContract", "::", "class", ")", "->", "where", "(", "[", "'likeable_id'", "=>", "$", "likeable", "->", "getKey", "(", ")", ",", "'likeable_type'", "=>", "$", "likeable", "->", "getMorphClass", "(", ")", ",", "'type_id'", "=>", "$", "this", "->", "getLikeTypeId", "(", "$", "type", ")", ",", "]", ")", "->", "delete", "(", ")", ";", "app", "(", "LikeCounterContract", "::", "class", ")", "->", "where", "(", "[", "'likeable_id'", "=>", "$", "likeable", "->", "getKey", "(", ")", ",", "'likeable_type'", "=>", "$", "likeable", "->", "getMorphClass", "(", ")", ",", "'type_id'", "=>", "$", "this", "->", "getLikeTypeId", "(", "$", "type", ")", ",", "]", ")", "->", "delete", "(", ")", ";", "}" ]
Remove all likes from likeable model. @param \Cog\Likeable\Contracts\Likeable $likeable @param string $type @return void @throws \Cog\Likeable\Exceptions\LikeTypeInvalidException
[ "Remove", "all", "likes", "from", "likeable", "model", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L265-L278
37,603
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.collectLikersOf
public function collectLikersOf(LikeableContract $likeable) { $userModel = $this->resolveUserModel(); $likersIds = $likeable->likes->pluck('user_id'); return $userModel::whereKey($likersIds)->get(); }
php
public function collectLikersOf(LikeableContract $likeable) { $userModel = $this->resolveUserModel(); $likersIds = $likeable->likes->pluck('user_id'); return $userModel::whereKey($likersIds)->get(); }
[ "public", "function", "collectLikersOf", "(", "LikeableContract", "$", "likeable", ")", "{", "$", "userModel", "=", "$", "this", "->", "resolveUserModel", "(", ")", ";", "$", "likersIds", "=", "$", "likeable", "->", "likes", "->", "pluck", "(", "'user_id'", ")", ";", "return", "$", "userModel", "::", "whereKey", "(", "$", "likersIds", ")", "->", "get", "(", ")", ";", "}" ]
Get collection of users who liked entity. @param \Cog\Likeable\Contracts\Likeable $likeable @return \Illuminate\Support\Collection
[ "Get", "collection", "of", "users", "who", "liked", "entity", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L286-L293
37,604
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.collectDislikersOf
public function collectDislikersOf(LikeableContract $likeable) { $userModel = $this->resolveUserModel(); $likersIds = $likeable->dislikes->pluck('user_id'); return $userModel::whereKey($likersIds)->get(); }
php
public function collectDislikersOf(LikeableContract $likeable) { $userModel = $this->resolveUserModel(); $likersIds = $likeable->dislikes->pluck('user_id'); return $userModel::whereKey($likersIds)->get(); }
[ "public", "function", "collectDislikersOf", "(", "LikeableContract", "$", "likeable", ")", "{", "$", "userModel", "=", "$", "this", "->", "resolveUserModel", "(", ")", ";", "$", "likersIds", "=", "$", "likeable", "->", "dislikes", "->", "pluck", "(", "'user_id'", ")", ";", "return", "$", "userModel", "::", "whereKey", "(", "$", "likersIds", ")", "->", "get", "(", ")", ";", "}" ]
Get collection of users who disliked entity. @param \Cog\Likeable\Contracts\Likeable $likeable @return \Illuminate\Support\Collection
[ "Get", "collection", "of", "users", "who", "disliked", "entity", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L301-L308
37,605
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.fetchLikesCounters
public function fetchLikesCounters($likeableType, $likeType) { /** @var \Illuminate\Database\Eloquent\Builder $likesCount */ $likesCount = app(LikeContract::class) ->select([ DB::raw('COUNT(*) AS count'), 'likeable_type', 'likeable_id', 'type_id', ]) ->where('likeable_type', $likeableType); if (!is_null($likeType)) { $likesCount->where('type_id', $this->getLikeTypeId($likeType)); } $likesCount->groupBy('likeable_id', 'type_id'); return $likesCount->get()->toArray(); }
php
public function fetchLikesCounters($likeableType, $likeType) { /** @var \Illuminate\Database\Eloquent\Builder $likesCount */ $likesCount = app(LikeContract::class) ->select([ DB::raw('COUNT(*) AS count'), 'likeable_type', 'likeable_id', 'type_id', ]) ->where('likeable_type', $likeableType); if (!is_null($likeType)) { $likesCount->where('type_id', $this->getLikeTypeId($likeType)); } $likesCount->groupBy('likeable_id', 'type_id'); return $likesCount->get()->toArray(); }
[ "public", "function", "fetchLikesCounters", "(", "$", "likeableType", ",", "$", "likeType", ")", "{", "/** @var \\Illuminate\\Database\\Eloquent\\Builder $likesCount */", "$", "likesCount", "=", "app", "(", "LikeContract", "::", "class", ")", "->", "select", "(", "[", "DB", "::", "raw", "(", "'COUNT(*) AS count'", ")", ",", "'likeable_type'", ",", "'likeable_id'", ",", "'type_id'", ",", "]", ")", "->", "where", "(", "'likeable_type'", ",", "$", "likeableType", ")", ";", "if", "(", "!", "is_null", "(", "$", "likeType", ")", ")", "{", "$", "likesCount", "->", "where", "(", "'type_id'", ",", "$", "this", "->", "getLikeTypeId", "(", "$", "likeType", ")", ")", ";", "}", "$", "likesCount", "->", "groupBy", "(", "'likeable_id'", ",", "'type_id'", ")", ";", "return", "$", "likesCount", "->", "get", "(", ")", "->", "toArray", "(", ")", ";", "}" ]
Fetch likes counters data. @param string $likeableType @param string $likeType @return array @throws \Cog\Likeable\Exceptions\LikeTypeInvalidException
[ "Fetch", "likes", "counters", "data", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L362-L381
37,606
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.getLikerUserId
protected function getLikerUserId($userId) { if (is_null($userId)) { $userId = $this->loggedInUserId(); } if (!$userId) { throw new LikerNotDefinedException(); } return $userId; }
php
protected function getLikerUserId($userId) { if (is_null($userId)) { $userId = $this->loggedInUserId(); } if (!$userId) { throw new LikerNotDefinedException(); } return $userId; }
[ "protected", "function", "getLikerUserId", "(", "$", "userId", ")", "{", "if", "(", "is_null", "(", "$", "userId", ")", ")", "{", "$", "userId", "=", "$", "this", "->", "loggedInUserId", "(", ")", ";", "}", "if", "(", "!", "$", "userId", ")", "{", "throw", "new", "LikerNotDefinedException", "(", ")", ";", "}", "return", "$", "userId", ";", "}" ]
Get current user id or get user id passed in. @param int $userId @return int @throws \Cog\Likeable\Exceptions\LikerNotDefinedException
[ "Get", "current", "user", "id", "or", "get", "user", "id", "passed", "in", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L391-L402
37,607
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.likeTypeRelations
private function likeTypeRelations($type) { $relations = [ LikeType::LIKE => [ 'likes', 'likesAndDislikes', ], LikeType::DISLIKE => [ 'dislikes', 'likesAndDislikes', ], ]; if (!isset($relations[$type])) { throw new LikeTypeInvalidException("Like type `{$type}` not supported"); } return $relations[$type]; }
php
private function likeTypeRelations($type) { $relations = [ LikeType::LIKE => [ 'likes', 'likesAndDislikes', ], LikeType::DISLIKE => [ 'dislikes', 'likesAndDislikes', ], ]; if (!isset($relations[$type])) { throw new LikeTypeInvalidException("Like type `{$type}` not supported"); } return $relations[$type]; }
[ "private", "function", "likeTypeRelations", "(", "$", "type", ")", "{", "$", "relations", "=", "[", "LikeType", "::", "LIKE", "=>", "[", "'likes'", ",", "'likesAndDislikes'", ",", "]", ",", "LikeType", "::", "DISLIKE", "=>", "[", "'dislikes'", ",", "'likesAndDislikes'", ",", "]", ",", "]", ";", "if", "(", "!", "isset", "(", "$", "relations", "[", "$", "type", "]", ")", ")", "{", "throw", "new", "LikeTypeInvalidException", "(", "\"Like type `{$type}` not supported\"", ")", ";", "}", "return", "$", "relations", "[", "$", "type", "]", ";", "}" ]
Resolve list of likeable relations by like type. @param string $type @return array @throws \Cog\Likeable\Exceptions\LikeTypeInvalidException
[ "Resolve", "list", "of", "likeable", "relations", "by", "like", "type", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L476-L494
37,608
cybercog/laravel-likeable
src/Providers/LikeableServiceProvider.php
LikeableServiceProvider.registerContracts
protected function registerContracts() { $this->app->bind(LikeContract::class, Like::class); $this->app->bind(LikeCounterContract::class, LikeCounter::class); $this->app->singleton(LikeableServiceContract::class, LikeableService::class); }
php
protected function registerContracts() { $this->app->bind(LikeContract::class, Like::class); $this->app->bind(LikeCounterContract::class, LikeCounter::class); $this->app->singleton(LikeableServiceContract::class, LikeableService::class); }
[ "protected", "function", "registerContracts", "(", ")", "{", "$", "this", "->", "app", "->", "bind", "(", "LikeContract", "::", "class", ",", "Like", "::", "class", ")", ";", "$", "this", "->", "app", "->", "bind", "(", "LikeCounterContract", "::", "class", ",", "LikeCounter", "::", "class", ")", ";", "$", "this", "->", "app", "->", "singleton", "(", "LikeableServiceContract", "::", "class", ",", "LikeableService", "::", "class", ")", ";", "}" ]
Register Likeable's classes in the container. @return void
[ "Register", "Likeable", "s", "classes", "in", "the", "container", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Providers/LikeableServiceProvider.php#L82-L87
37,609
cybercog/laravel-likeable
src/Traits/Likeable.php
Likeable.scopeWhereDislikedBy
public function scopeWhereDislikedBy(Builder $query, $userId = null) { return app(LikeableServiceContract::class) ->scopeWhereLikedBy($query, LikeType::DISLIKE, $userId); }
php
public function scopeWhereDislikedBy(Builder $query, $userId = null) { return app(LikeableServiceContract::class) ->scopeWhereLikedBy($query, LikeType::DISLIKE, $userId); }
[ "public", "function", "scopeWhereDislikedBy", "(", "Builder", "$", "query", ",", "$", "userId", "=", "null", ")", "{", "return", "app", "(", "LikeableServiceContract", "::", "class", ")", "->", "scopeWhereLikedBy", "(", "$", "query", ",", "LikeType", "::", "DISLIKE", ",", "$", "userId", ")", ";", "}" ]
Fetch records that are disliked by a given user id. @param \Illuminate\Database\Eloquent\Builder $query @param int|null $userId @return \Illuminate\Database\Eloquent\Builder @throws \Cog\Likeable\Exceptions\LikerNotDefinedException
[ "Fetch", "records", "that", "are", "disliked", "by", "a", "given", "user", "id", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Traits/Likeable.php#L184-L188
37,610
cybercog/laravel-likeable
src/Traits/Likeable.php
Likeable.like
public function like($userId = null) { app(LikeableServiceContract::class)->addLikeTo($this, LikeType::LIKE, $userId); }
php
public function like($userId = null) { app(LikeableServiceContract::class)->addLikeTo($this, LikeType::LIKE, $userId); }
[ "public", "function", "like", "(", "$", "userId", "=", "null", ")", "{", "app", "(", "LikeableServiceContract", "::", "class", ")", "->", "addLikeTo", "(", "$", "this", ",", "LikeType", "::", "LIKE", ",", "$", "userId", ")", ";", "}" ]
Add a like for model by the given user. @param mixed $userId If null will use currently logged in user. @return void @throws \Cog\Likeable\Exceptions\LikerNotDefinedException
[ "Add", "a", "like", "for", "model", "by", "the", "given", "user", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Traits/Likeable.php#L224-L227
37,611
cybercog/laravel-likeable
src/Traits/Likeable.php
Likeable.dislike
public function dislike($userId = null) { app(LikeableServiceContract::class)->addLikeTo($this, LikeType::DISLIKE, $userId); }
php
public function dislike($userId = null) { app(LikeableServiceContract::class)->addLikeTo($this, LikeType::DISLIKE, $userId); }
[ "public", "function", "dislike", "(", "$", "userId", "=", "null", ")", "{", "app", "(", "LikeableServiceContract", "::", "class", ")", "->", "addLikeTo", "(", "$", "this", ",", "LikeType", "::", "DISLIKE", ",", "$", "userId", ")", ";", "}" ]
Add a dislike for model by the given user. @param mixed $userId If null will use currently logged in user. @return void @throws \Cog\Likeable\Exceptions\LikerNotDefinedException
[ "Add", "a", "dislike", "for", "model", "by", "the", "given", "user", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Traits/Likeable.php#L284-L287
37,612
cybercog/laravel-likeable
src/Traits/Likeable.php
Likeable.undislike
public function undislike($userId = null) { app(LikeableServiceContract::class)->removeLikeFrom($this, LikeType::DISLIKE, $userId); }
php
public function undislike($userId = null) { app(LikeableServiceContract::class)->removeLikeFrom($this, LikeType::DISLIKE, $userId); }
[ "public", "function", "undislike", "(", "$", "userId", "=", "null", ")", "{", "app", "(", "LikeableServiceContract", "::", "class", ")", "->", "removeLikeFrom", "(", "$", "this", ",", "LikeType", "::", "DISLIKE", ",", "$", "userId", ")", ";", "}" ]
Remove a dislike from this record for the given user. @param int|null $userId If null will use currently logged in user. @return void @throws \Cog\Likeable\Exceptions\LikerNotDefinedException
[ "Remove", "a", "dislike", "from", "this", "record", "for", "the", "given", "user", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Traits/Likeable.php#L297-L300
37,613
cybercog/laravel-likeable
src/Traits/Likeable.php
Likeable.dislikeToggle
public function dislikeToggle($userId = null) { app(LikeableServiceContract::class)->toggleLikeOf($this, LikeType::DISLIKE, $userId); }
php
public function dislikeToggle($userId = null) { app(LikeableServiceContract::class)->toggleLikeOf($this, LikeType::DISLIKE, $userId); }
[ "public", "function", "dislikeToggle", "(", "$", "userId", "=", "null", ")", "{", "app", "(", "LikeableServiceContract", "::", "class", ")", "->", "toggleLikeOf", "(", "$", "this", ",", "LikeType", "::", "DISLIKE", ",", "$", "userId", ")", ";", "}" ]
Toggle dislike for model by the given user. @param mixed $userId If null will use currently logged in user. @return void @throws \Cog\Likeable\Exceptions\LikerNotDefinedException
[ "Toggle", "dislike", "for", "model", "by", "the", "given", "user", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Traits/Likeable.php#L310-L313
37,614
cybercog/laravel-likeable
src/Traits/Likeable.php
Likeable.disliked
public function disliked($userId = null) { return app(LikeableServiceContract::class)->isLiked($this, LikeType::DISLIKE, $userId); }
php
public function disliked($userId = null) { return app(LikeableServiceContract::class)->isLiked($this, LikeType::DISLIKE, $userId); }
[ "public", "function", "disliked", "(", "$", "userId", "=", "null", ")", "{", "return", "app", "(", "LikeableServiceContract", "::", "class", ")", "->", "isLiked", "(", "$", "this", ",", "LikeType", "::", "DISLIKE", ",", "$", "userId", ")", ";", "}" ]
Has the user already disliked likeable model. @param int|null $userId @return bool
[ "Has", "the", "user", "already", "disliked", "likeable", "model", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Traits/Likeable.php#L321-L324
37,615
cybercog/laravel-likeable
src/Console/LikeableRecountCommand.php
LikeableRecountCommand.recountLikesOfAllModelTypes
protected function recountLikesOfAllModelTypes() { $likeableTypes = app(LikeContract::class)->groupBy('likeable_type')->get(); foreach ($likeableTypes as $like) { $this->recountLikesOfModelType($like->likeable_type); } }
php
protected function recountLikesOfAllModelTypes() { $likeableTypes = app(LikeContract::class)->groupBy('likeable_type')->get(); foreach ($likeableTypes as $like) { $this->recountLikesOfModelType($like->likeable_type); } }
[ "protected", "function", "recountLikesOfAllModelTypes", "(", ")", "{", "$", "likeableTypes", "=", "app", "(", "LikeContract", "::", "class", ")", "->", "groupBy", "(", "'likeable_type'", ")", "->", "get", "(", ")", ";", "foreach", "(", "$", "likeableTypes", "as", "$", "like", ")", "{", "$", "this", "->", "recountLikesOfModelType", "(", "$", "like", "->", "likeable_type", ")", ";", "}", "}" ]
Recount likes of all model types. @return void @throws \Cog\Likeable\Exceptions\ModelInvalidException
[ "Recount", "likes", "of", "all", "model", "types", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Console/LikeableRecountCommand.php#L87-L93
37,616
cybercog/laravel-likeable
src/Console/LikeableRecountCommand.php
LikeableRecountCommand.recountLikesOfModelType
protected function recountLikesOfModelType($modelType) { $modelType = $this->normalizeModelType($modelType); $counters = $this->service->fetchLikesCounters($modelType, $this->likeType); $this->service->removeLikeCountersOfType($modelType, $this->likeType); DB::table(app(LikeCounterContract::class)->getTable())->insert($counters); $this->info('All [' . $modelType . '] records likes has been recounted.'); }
php
protected function recountLikesOfModelType($modelType) { $modelType = $this->normalizeModelType($modelType); $counters = $this->service->fetchLikesCounters($modelType, $this->likeType); $this->service->removeLikeCountersOfType($modelType, $this->likeType); DB::table(app(LikeCounterContract::class)->getTable())->insert($counters); $this->info('All [' . $modelType . '] records likes has been recounted.'); }
[ "protected", "function", "recountLikesOfModelType", "(", "$", "modelType", ")", "{", "$", "modelType", "=", "$", "this", "->", "normalizeModelType", "(", "$", "modelType", ")", ";", "$", "counters", "=", "$", "this", "->", "service", "->", "fetchLikesCounters", "(", "$", "modelType", ",", "$", "this", "->", "likeType", ")", ";", "$", "this", "->", "service", "->", "removeLikeCountersOfType", "(", "$", "modelType", ",", "$", "this", "->", "likeType", ")", ";", "DB", "::", "table", "(", "app", "(", "LikeCounterContract", "::", "class", ")", "->", "getTable", "(", ")", ")", "->", "insert", "(", "$", "counters", ")", ";", "$", "this", "->", "info", "(", "'All ['", ".", "$", "modelType", ".", "'] records likes has been recounted.'", ")", ";", "}" ]
Recount likes of model type. @param string $modelType @return void @throws \Cog\Likeable\Exceptions\ModelInvalidException
[ "Recount", "likes", "of", "model", "type", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Console/LikeableRecountCommand.php#L103-L114
37,617
waza-ari/monolog-mysql
src/MySQLHandler/MySQLHandler.php
MySQLHandler.prepareStatement
private function prepareStatement() { //Prepare statement $columns = ""; $fields = ""; foreach ($this->fields as $key => $f) { if ($f == 'id') { continue; } if ($key == 1) { $columns .= "$f"; $fields .= ":$f"; continue; } $columns .= ", $f"; $fields .= ", :$f"; } $this->statement = $this->pdo->prepare( 'INSERT INTO `' . $this->table . '` (' . $columns . ') VALUES (' . $fields . ')' ); }
php
private function prepareStatement() { //Prepare statement $columns = ""; $fields = ""; foreach ($this->fields as $key => $f) { if ($f == 'id') { continue; } if ($key == 1) { $columns .= "$f"; $fields .= ":$f"; continue; } $columns .= ", $f"; $fields .= ", :$f"; } $this->statement = $this->pdo->prepare( 'INSERT INTO `' . $this->table . '` (' . $columns . ') VALUES (' . $fields . ')' ); }
[ "private", "function", "prepareStatement", "(", ")", "{", "//Prepare statement", "$", "columns", "=", "\"\"", ";", "$", "fields", "=", "\"\"", ";", "foreach", "(", "$", "this", "->", "fields", "as", "$", "key", "=>", "$", "f", ")", "{", "if", "(", "$", "f", "==", "'id'", ")", "{", "continue", ";", "}", "if", "(", "$", "key", "==", "1", ")", "{", "$", "columns", ".=", "\"$f\"", ";", "$", "fields", ".=", "\":$f\"", ";", "continue", ";", "}", "$", "columns", ".=", "\", $f\"", ";", "$", "fields", ".=", "\", :$f\"", ";", "}", "$", "this", "->", "statement", "=", "$", "this", "->", "pdo", "->", "prepare", "(", "'INSERT INTO `'", ".", "$", "this", "->", "table", ".", "'` ('", ".", "$", "columns", ".", "') VALUES ('", ".", "$", "fields", ".", "')'", ")", ";", "}" ]
Prepare the sql statment depending on the fields that should be written to the database
[ "Prepare", "the", "sql", "statment", "depending", "on", "the", "fields", "that", "should", "be", "written", "to", "the", "database" ]
5b3d75a59254f27b05f528a74df82bd1dd87f182
https://github.com/waza-ari/monolog-mysql/blob/5b3d75a59254f27b05f528a74df82bd1dd87f182/src/MySQLHandler/MySQLHandler.php#L133-L155
37,618
laravel-admin-extensions/env-manager
src/Env.php
Env.getEnv
private function getEnv($id = null) { $string = file_get_contents($this->env); $string = preg_split('/\n+/', $string); $array = []; foreach ($string as $k => $one) { if (preg_match('/^(#\s)/', $one) === 1 || preg_match('/^([\\n\\r]+)/', $one)) { continue; } $entry = explode("=", $one, 2); if (!empty($entry[0])) { $array[] = ['id' => $k + 1, 'key' => $entry[0], 'value' => isset($entry[1]) ? $entry[1] : null]; } } if (empty($id)) { return $array; } $index = array_search($id, array_column($array, 'id')); return $array[$index]; }
php
private function getEnv($id = null) { $string = file_get_contents($this->env); $string = preg_split('/\n+/', $string); $array = []; foreach ($string as $k => $one) { if (preg_match('/^(#\s)/', $one) === 1 || preg_match('/^([\\n\\r]+)/', $one)) { continue; } $entry = explode("=", $one, 2); if (!empty($entry[0])) { $array[] = ['id' => $k + 1, 'key' => $entry[0], 'value' => isset($entry[1]) ? $entry[1] : null]; } } if (empty($id)) { return $array; } $index = array_search($id, array_column($array, 'id')); return $array[$index]; }
[ "private", "function", "getEnv", "(", "$", "id", "=", "null", ")", "{", "$", "string", "=", "file_get_contents", "(", "$", "this", "->", "env", ")", ";", "$", "string", "=", "preg_split", "(", "'/\\n+/'", ",", "$", "string", ")", ";", "$", "array", "=", "[", "]", ";", "foreach", "(", "$", "string", "as", "$", "k", "=>", "$", "one", ")", "{", "if", "(", "preg_match", "(", "'/^(#\\s)/'", ",", "$", "one", ")", "===", "1", "||", "preg_match", "(", "'/^([\\\\n\\\\r]+)/'", ",", "$", "one", ")", ")", "{", "continue", ";", "}", "$", "entry", "=", "explode", "(", "\"=\"", ",", "$", "one", ",", "2", ")", ";", "if", "(", "!", "empty", "(", "$", "entry", "[", "0", "]", ")", ")", "{", "$", "array", "[", "]", "=", "[", "'id'", "=>", "$", "k", "+", "1", ",", "'key'", "=>", "$", "entry", "[", "0", "]", ",", "'value'", "=>", "isset", "(", "$", "entry", "[", "1", "]", ")", "?", "$", "entry", "[", "1", "]", ":", "null", "]", ";", "}", "}", "if", "(", "empty", "(", "$", "id", ")", ")", "{", "return", "$", "array", ";", "}", "$", "index", "=", "array_search", "(", "$", "id", ",", "array_column", "(", "$", "array", ",", "'id'", ")", ")", ";", "return", "$", "array", "[", "$", "index", "]", ";", "}" ]
Get .env variable. @param null $id @return array|mixed
[ "Get", ".", "env", "variable", "." ]
f9c83b213e97a36bb500b25a5357aae2d6435958
https://github.com/laravel-admin-extensions/env-manager/blob/f9c83b213e97a36bb500b25a5357aae2d6435958/src/Env.php#L74-L94
37,619
laravel-admin-extensions/env-manager
src/Env.php
Env.setEnv
private function setEnv($key, $value) { $array = $this->getEnv(); $index = array_search($key, array_column($array, 'key')); if ($index !== false) { $array[$index]['value'] = $value; // 更新 } else { array_push($array, ['key' => $key, 'value' => $value]); // 新增 } return $this->saveEnv($array); }
php
private function setEnv($key, $value) { $array = $this->getEnv(); $index = array_search($key, array_column($array, 'key')); if ($index !== false) { $array[$index]['value'] = $value; // 更新 } else { array_push($array, ['key' => $key, 'value' => $value]); // 新增 } return $this->saveEnv($array); }
[ "private", "function", "setEnv", "(", "$", "key", ",", "$", "value", ")", "{", "$", "array", "=", "$", "this", "->", "getEnv", "(", ")", ";", "$", "index", "=", "array_search", "(", "$", "key", ",", "array_column", "(", "$", "array", ",", "'key'", ")", ")", ";", "if", "(", "$", "index", "!==", "false", ")", "{", "$", "array", "[", "$", "index", "]", "[", "'value'", "]", "=", "$", "value", ";", "// 更新", "}", "else", "{", "array_push", "(", "$", "array", ",", "[", "'key'", "=>", "$", "key", ",", "'value'", "=>", "$", "value", "]", ")", ";", "// 新增", "}", "return", "$", "this", "->", "saveEnv", "(", "$", "array", ")", ";", "}" ]
Update or create .env variable. @param $key @param $value @return bool
[ "Update", "or", "create", ".", "env", "variable", "." ]
f9c83b213e97a36bb500b25a5357aae2d6435958
https://github.com/laravel-admin-extensions/env-manager/blob/f9c83b213e97a36bb500b25a5357aae2d6435958/src/Env.php#L102-L112
37,620
laravel-admin-extensions/env-manager
src/Env.php
Env.saveEnv
private function saveEnv($array) { if (is_array($array)) { $newArray = []; $i = 0; foreach ($array as $env) { if (preg_match('/\s/', $env['value']) > 0 && (strpos($env['value'], '"') > 0 && strpos($env['value'], '"', -0) > 0)) { $env['value'] = '"'.$env['value'].'"'; } $newArray[$i] = $env['key']."=".$env['value']; $i++; } $newArray = implode("\n", $newArray); file_put_contents($this->env, $newArray); return true; } return false; }
php
private function saveEnv($array) { if (is_array($array)) { $newArray = []; $i = 0; foreach ($array as $env) { if (preg_match('/\s/', $env['value']) > 0 && (strpos($env['value'], '"') > 0 && strpos($env['value'], '"', -0) > 0)) { $env['value'] = '"'.$env['value'].'"'; } $newArray[$i] = $env['key']."=".$env['value']; $i++; } $newArray = implode("\n", $newArray); file_put_contents($this->env, $newArray); return true; } return false; }
[ "private", "function", "saveEnv", "(", "$", "array", ")", "{", "if", "(", "is_array", "(", "$", "array", ")", ")", "{", "$", "newArray", "=", "[", "]", ";", "$", "i", "=", "0", ";", "foreach", "(", "$", "array", "as", "$", "env", ")", "{", "if", "(", "preg_match", "(", "'/\\s/'", ",", "$", "env", "[", "'value'", "]", ")", ">", "0", "&&", "(", "strpos", "(", "$", "env", "[", "'value'", "]", ",", "'\"'", ")", ">", "0", "&&", "strpos", "(", "$", "env", "[", "'value'", "]", ",", "'\"'", ",", "-", "0", ")", ">", "0", ")", ")", "{", "$", "env", "[", "'value'", "]", "=", "'\"'", ".", "$", "env", "[", "'value'", "]", ".", "'\"'", ";", "}", "$", "newArray", "[", "$", "i", "]", "=", "$", "env", "[", "'key'", "]", ".", "\"=\"", ".", "$", "env", "[", "'value'", "]", ";", "$", "i", "++", ";", "}", "$", "newArray", "=", "implode", "(", "\"\\n\"", ",", "$", "newArray", ")", ";", "file_put_contents", "(", "$", "this", "->", "env", ",", "$", "newArray", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Save .env variable. @param $array @return bool
[ "Save", ".", "env", "variable", "." ]
f9c83b213e97a36bb500b25a5357aae2d6435958
https://github.com/laravel-admin-extensions/env-manager/blob/f9c83b213e97a36bb500b25a5357aae2d6435958/src/Env.php#L119-L137
37,621
LeaseWeb/LswMemcacheBundle
Command/StatisticsCommand.php
StatisticsCommand.interact
protected function interact(InputInterface $input, OutputInterface $output) { if (!$input->getArgument('pool')) { $pool = (new InteractHelper())->askForPool($this, $input, $output); $input->setArgument('pool', $pool); } }
php
protected function interact(InputInterface $input, OutputInterface $output) { if (!$input->getArgument('pool')) { $pool = (new InteractHelper())->askForPool($this, $input, $output); $input->setArgument('pool', $pool); } }
[ "protected", "function", "interact", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "if", "(", "!", "$", "input", "->", "getArgument", "(", "'pool'", ")", ")", "{", "$", "pool", "=", "(", "new", "InteractHelper", "(", ")", ")", "->", "askForPool", "(", "$", "this", ",", "$", "input", ",", "$", "output", ")", ";", "$", "input", "->", "setArgument", "(", "'pool'", ",", "$", "pool", ")", ";", "}", "}" ]
Choose the pool @param InputInterface $input Input interface @param OutputInterface $output Output interface @see Command @return mixed
[ "Choose", "the", "pool" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/Command/StatisticsCommand.php#L62-L68
37,622
LeaseWeb/LswMemcacheBundle
Command/StatisticsCommand.php
StatisticsCommand.formatStats
protected function formatStats($stats) { if (!$stats) { return "No statistics returned.\n"; } $out = "Servers found: " . count($stats) . "\n\n"; foreach ($stats as $host => $item) { if (!is_array($item) || count($item) == 0) { $out .= " <error>" . $host . "</error>\n"; continue; } $out .= "<info>Host:\t" . $host . "</info>\n"; $out .= "\tUsage: " . $this->formatUsage($item['bytes'], $item['limit_maxbytes']) . "\n"; $out .= "\tUptime: " . $this->formatUptime($item['uptime']) . "\n"; $out .= "\tOpen Connections: " . $item['curr_connections'] . "\n"; $out .= "\tHits: " . $item['get_hits'] . "\n"; $out .= "\tMisses: " . $item['get_misses'] . "\n"; if ($item['get_hits'] + $item['get_misses'] > 0 ) { $out .= "\tHelpfulness: " . round($item['get_hits'] / ($item['get_hits'] + $item['get_misses']) * 100, 2) . "%\n"; } } return $out; }
php
protected function formatStats($stats) { if (!$stats) { return "No statistics returned.\n"; } $out = "Servers found: " . count($stats) . "\n\n"; foreach ($stats as $host => $item) { if (!is_array($item) || count($item) == 0) { $out .= " <error>" . $host . "</error>\n"; continue; } $out .= "<info>Host:\t" . $host . "</info>\n"; $out .= "\tUsage: " . $this->formatUsage($item['bytes'], $item['limit_maxbytes']) . "\n"; $out .= "\tUptime: " . $this->formatUptime($item['uptime']) . "\n"; $out .= "\tOpen Connections: " . $item['curr_connections'] . "\n"; $out .= "\tHits: " . $item['get_hits'] . "\n"; $out .= "\tMisses: " . $item['get_misses'] . "\n"; if ($item['get_hits'] + $item['get_misses'] > 0 ) { $out .= "\tHelpfulness: " . round($item['get_hits'] / ($item['get_hits'] + $item['get_misses']) * 100, 2) . "%\n"; } } return $out; }
[ "protected", "function", "formatStats", "(", "$", "stats", ")", "{", "if", "(", "!", "$", "stats", ")", "{", "return", "\"No statistics returned.\\n\"", ";", "}", "$", "out", "=", "\"Servers found: \"", ".", "count", "(", "$", "stats", ")", ".", "\"\\n\\n\"", ";", "foreach", "(", "$", "stats", "as", "$", "host", "=>", "$", "item", ")", "{", "if", "(", "!", "is_array", "(", "$", "item", ")", "||", "count", "(", "$", "item", ")", "==", "0", ")", "{", "$", "out", ".=", "\" <error>\"", ".", "$", "host", ".", "\"</error>\\n\"", ";", "continue", ";", "}", "$", "out", ".=", "\"<info>Host:\\t\"", ".", "$", "host", ".", "\"</info>\\n\"", ";", "$", "out", ".=", "\"\\tUsage: \"", ".", "$", "this", "->", "formatUsage", "(", "$", "item", "[", "'bytes'", "]", ",", "$", "item", "[", "'limit_maxbytes'", "]", ")", ".", "\"\\n\"", ";", "$", "out", ".=", "\"\\tUptime: \"", ".", "$", "this", "->", "formatUptime", "(", "$", "item", "[", "'uptime'", "]", ")", ".", "\"\\n\"", ";", "$", "out", ".=", "\"\\tOpen Connections: \"", ".", "$", "item", "[", "'curr_connections'", "]", ".", "\"\\n\"", ";", "$", "out", ".=", "\"\\tHits: \"", ".", "$", "item", "[", "'get_hits'", "]", ".", "\"\\n\"", ";", "$", "out", ".=", "\"\\tMisses: \"", ".", "$", "item", "[", "'get_misses'", "]", ".", "\"\\n\"", ";", "if", "(", "$", "item", "[", "'get_hits'", "]", "+", "$", "item", "[", "'get_misses'", "]", ">", "0", ")", "{", "$", "out", ".=", "\"\\tHelpfulness: \"", ".", "round", "(", "$", "item", "[", "'get_hits'", "]", "/", "(", "$", "item", "[", "'get_hits'", "]", "+", "$", "item", "[", "'get_misses'", "]", ")", "*", "100", ",", "2", ")", ".", "\"%\\n\"", ";", "}", "}", "return", "$", "out", ";", "}" ]
Format the raw array for the command line report @param array $stats An array of memcache::extendedstats @return string ConsoleComponent-formatted output, suitable for ->writeln() usage
[ "Format", "the", "raw", "array", "for", "the", "command", "line", "report" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/Command/StatisticsCommand.php#L77-L103
37,623
LeaseWeb/LswMemcacheBundle
Command/StatisticsCommand.php
StatisticsCommand.formatUptime
protected function formatUptime($uptime ) { $days = floor($uptime / 24 / 60 / 60); $daysRemainder = $uptime - ($days * 24 * 60 * 60); $hours = floor($daysRemainder / 60 / 60); $hoursRemainder = $daysRemainder - ($hours * 60 * 60); $minutes = floor($hoursRemainder / 60); $minutesRemainder = $hoursRemainder - ($minutes * 60); $seconds = $minutesRemainder; $out = $uptime . ' seconds ('; if ($days > 0) { $out .= $days . ' days, '; } if ($hours > 0) { $out .= $hours . ' hours, '; } if ($minutes > 0) { $out .= $minutes . ' minutes, '; } if ($seconds > 0) { $out .= $seconds . ' seconds'; } return $out . ')'; }
php
protected function formatUptime($uptime ) { $days = floor($uptime / 24 / 60 / 60); $daysRemainder = $uptime - ($days * 24 * 60 * 60); $hours = floor($daysRemainder / 60 / 60); $hoursRemainder = $daysRemainder - ($hours * 60 * 60); $minutes = floor($hoursRemainder / 60); $minutesRemainder = $hoursRemainder - ($minutes * 60); $seconds = $minutesRemainder; $out = $uptime . ' seconds ('; if ($days > 0) { $out .= $days . ' days, '; } if ($hours > 0) { $out .= $hours . ' hours, '; } if ($minutes > 0) { $out .= $minutes . ' minutes, '; } if ($seconds > 0) { $out .= $seconds . ' seconds'; } return $out . ')'; }
[ "protected", "function", "formatUptime", "(", "$", "uptime", ")", "{", "$", "days", "=", "floor", "(", "$", "uptime", "/", "24", "/", "60", "/", "60", ")", ";", "$", "daysRemainder", "=", "$", "uptime", "-", "(", "$", "days", "*", "24", "*", "60", "*", "60", ")", ";", "$", "hours", "=", "floor", "(", "$", "daysRemainder", "/", "60", "/", "60", ")", ";", "$", "hoursRemainder", "=", "$", "daysRemainder", "-", "(", "$", "hours", "*", "60", "*", "60", ")", ";", "$", "minutes", "=", "floor", "(", "$", "hoursRemainder", "/", "60", ")", ";", "$", "minutesRemainder", "=", "$", "hoursRemainder", "-", "(", "$", "minutes", "*", "60", ")", ";", "$", "seconds", "=", "$", "minutesRemainder", ";", "$", "out", "=", "$", "uptime", ".", "' seconds ('", ";", "if", "(", "$", "days", ">", "0", ")", "{", "$", "out", ".=", "$", "days", ".", "' days, '", ";", "}", "if", "(", "$", "hours", ">", "0", ")", "{", "$", "out", ".=", "$", "hours", ".", "' hours, '", ";", "}", "if", "(", "$", "minutes", ">", "0", ")", "{", "$", "out", ".=", "$", "minutes", ".", "' minutes, '", ";", "}", "if", "(", "$", "seconds", ">", "0", ")", "{", "$", "out", ".=", "$", "seconds", ".", "' seconds'", ";", "}", "return", "$", "out", ".", "')'", ";", "}" ]
Formats the uptime to be friendlier @param integer $uptime Cache server uptime (in seconds) @return string A short string with friendly formatting
[ "Formats", "the", "uptime", "to", "be", "friendlier" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/Command/StatisticsCommand.php#L133-L158
37,624
LeaseWeb/LswMemcacheBundle
Firewall/FirewallHandler.php
FirewallHandler.onKernelRequest
public function onKernelRequest(GetResponseEvent $event) { if (!$event->isMasterRequest()) { return; } $request = $event->getRequest(); if ($this->reverseProxies) { $request->setTrustedProxies($this->reverseProxies); } if ($this->xForwardedFor) { $request->setTrustedHeaderName(Request::HEADER_CLIENT_IP, $this->xForwardedFor); } $ip = $request->getClientIp(); $start = microtime(true); $this->key=$this->prefix.'_'.$ip; $this->memcache->add($this->key,0,false,$this->lockMaxWait); while (true) { $this->incremented = true; if ($this->memcache->increment($this->key)<=$this->concurrency) { break; } $this->incremented = false; $this->memcache->decrement($this->key); if (!$this->spinLockWait || microtime(true)-$start>$this->lockMaxWait) { throw new TooManyRequestsHttpException(); } usleep($this->spinLockWait); } }
php
public function onKernelRequest(GetResponseEvent $event) { if (!$event->isMasterRequest()) { return; } $request = $event->getRequest(); if ($this->reverseProxies) { $request->setTrustedProxies($this->reverseProxies); } if ($this->xForwardedFor) { $request->setTrustedHeaderName(Request::HEADER_CLIENT_IP, $this->xForwardedFor); } $ip = $request->getClientIp(); $start = microtime(true); $this->key=$this->prefix.'_'.$ip; $this->memcache->add($this->key,0,false,$this->lockMaxWait); while (true) { $this->incremented = true; if ($this->memcache->increment($this->key)<=$this->concurrency) { break; } $this->incremented = false; $this->memcache->decrement($this->key); if (!$this->spinLockWait || microtime(true)-$start>$this->lockMaxWait) { throw new TooManyRequestsHttpException(); } usleep($this->spinLockWait); } }
[ "public", "function", "onKernelRequest", "(", "GetResponseEvent", "$", "event", ")", "{", "if", "(", "!", "$", "event", "->", "isMasterRequest", "(", ")", ")", "{", "return", ";", "}", "$", "request", "=", "$", "event", "->", "getRequest", "(", ")", ";", "if", "(", "$", "this", "->", "reverseProxies", ")", "{", "$", "request", "->", "setTrustedProxies", "(", "$", "this", "->", "reverseProxies", ")", ";", "}", "if", "(", "$", "this", "->", "xForwardedFor", ")", "{", "$", "request", "->", "setTrustedHeaderName", "(", "Request", "::", "HEADER_CLIENT_IP", ",", "$", "this", "->", "xForwardedFor", ")", ";", "}", "$", "ip", "=", "$", "request", "->", "getClientIp", "(", ")", ";", "$", "start", "=", "microtime", "(", "true", ")", ";", "$", "this", "->", "key", "=", "$", "this", "->", "prefix", ".", "'_'", ".", "$", "ip", ";", "$", "this", "->", "memcache", "->", "add", "(", "$", "this", "->", "key", ",", "0", ",", "false", ",", "$", "this", "->", "lockMaxWait", ")", ";", "while", "(", "true", ")", "{", "$", "this", "->", "incremented", "=", "true", ";", "if", "(", "$", "this", "->", "memcache", "->", "increment", "(", "$", "this", "->", "key", ")", "<=", "$", "this", "->", "concurrency", ")", "{", "break", ";", "}", "$", "this", "->", "incremented", "=", "false", ";", "$", "this", "->", "memcache", "->", "decrement", "(", "$", "this", "->", "key", ")", ";", "if", "(", "!", "$", "this", "->", "spinLockWait", "||", "microtime", "(", "true", ")", "-", "$", "start", ">", "$", "this", "->", "lockMaxWait", ")", "{", "throw", "new", "TooManyRequestsHttpException", "(", ")", ";", "}", "usleep", "(", "$", "this", "->", "spinLockWait", ")", ";", "}", "}" ]
If the current concurrency is too high, delay or throw a TooManyRequestsHttpException @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event Event @throws \Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException
[ "If", "the", "current", "concurrency", "is", "too", "high", "delay", "or", "throw", "a", "TooManyRequestsHttpException" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/Firewall/FirewallHandler.php#L107-L139
37,625
LeaseWeb/LswMemcacheBundle
Firewall/FirewallHandler.php
FirewallHandler.onKernelTerminate
public function onKernelTerminate(PostResponseEvent $event) { if (!$this->incremented) { return; } $this->incremented = false; $this->memcache->decrement($this->key); }
php
public function onKernelTerminate(PostResponseEvent $event) { if (!$this->incremented) { return; } $this->incremented = false; $this->memcache->decrement($this->key); }
[ "public", "function", "onKernelTerminate", "(", "PostResponseEvent", "$", "event", ")", "{", "if", "(", "!", "$", "this", "->", "incremented", ")", "{", "return", ";", "}", "$", "this", "->", "incremented", "=", "false", ";", "$", "this", "->", "memcache", "->", "decrement", "(", "$", "this", "->", "key", ")", ";", "}" ]
If the current request has ended, decrement concurrency counter @param \Symfony\Component\HttpKernel\Event\PostResponseEvent $event Event
[ "If", "the", "current", "request", "has", "ended", "decrement", "concurrency", "counter" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/Firewall/FirewallHandler.php#L147-L155
37,626
LeaseWeb/LswMemcacheBundle
DependencyInjection/Configuration.php
Configuration.addClientsSection
private function addClientsSection() { $tree = new TreeBuilder(); $node = $tree->root('pools'); $node ->requiresAtLeastOneElement() ->useAttributeAsKey('name') ->prototype('array') ->children() ->arrayNode('servers') ->requiresAtLeastOneElement() ->prototype('array') ->children() ->scalarNode('host') ->cannotBeEmpty() ->isRequired() ->end() ->scalarNode('tcp_port') ->defaultValue(11211) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('port must be numeric') ->end() ->end() ->scalarNode('udp_port') ->defaultValue(0) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('port must be numeric') ->end() ->end() ->booleanNode('persistent') ->defaultTrue() ->end() ->scalarNode('weight') ->defaultValue(1) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('weight must be numeric') ->end() ->end() ->scalarNode('timeout') ->defaultValue(1) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('timeout must be numeric') ->end() ->end() ->scalarNode('retry_interval') ->defaultValue(15) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('retry_interval must be numeric') ->end() ->end() ->end() ->end() ->end() ->append($this->addMemcacheOptionsSection()) ->end() ->end() ->end(); return $node; }
php
private function addClientsSection() { $tree = new TreeBuilder(); $node = $tree->root('pools'); $node ->requiresAtLeastOneElement() ->useAttributeAsKey('name') ->prototype('array') ->children() ->arrayNode('servers') ->requiresAtLeastOneElement() ->prototype('array') ->children() ->scalarNode('host') ->cannotBeEmpty() ->isRequired() ->end() ->scalarNode('tcp_port') ->defaultValue(11211) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('port must be numeric') ->end() ->end() ->scalarNode('udp_port') ->defaultValue(0) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('port must be numeric') ->end() ->end() ->booleanNode('persistent') ->defaultTrue() ->end() ->scalarNode('weight') ->defaultValue(1) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('weight must be numeric') ->end() ->end() ->scalarNode('timeout') ->defaultValue(1) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('timeout must be numeric') ->end() ->end() ->scalarNode('retry_interval') ->defaultValue(15) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('retry_interval must be numeric') ->end() ->end() ->end() ->end() ->end() ->append($this->addMemcacheOptionsSection()) ->end() ->end() ->end(); return $node; }
[ "private", "function", "addClientsSection", "(", ")", "{", "$", "tree", "=", "new", "TreeBuilder", "(", ")", ";", "$", "node", "=", "$", "tree", "->", "root", "(", "'pools'", ")", ";", "$", "node", "->", "requiresAtLeastOneElement", "(", ")", "->", "useAttributeAsKey", "(", "'name'", ")", "->", "prototype", "(", "'array'", ")", "->", "children", "(", ")", "->", "arrayNode", "(", "'servers'", ")", "->", "requiresAtLeastOneElement", "(", ")", "->", "prototype", "(", "'array'", ")", "->", "children", "(", ")", "->", "scalarNode", "(", "'host'", ")", "->", "cannotBeEmpty", "(", ")", "->", "isRequired", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'tcp_port'", ")", "->", "defaultValue", "(", "11211", ")", "->", "validate", "(", ")", "->", "ifTrue", "(", "function", "(", "$", "v", ")", "{", "return", "!", "is_numeric", "(", "$", "v", ")", ";", "}", ")", "->", "thenInvalid", "(", "'port must be numeric'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'udp_port'", ")", "->", "defaultValue", "(", "0", ")", "->", "validate", "(", ")", "->", "ifTrue", "(", "function", "(", "$", "v", ")", "{", "return", "!", "is_numeric", "(", "$", "v", ")", ";", "}", ")", "->", "thenInvalid", "(", "'port must be numeric'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "booleanNode", "(", "'persistent'", ")", "->", "defaultTrue", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'weight'", ")", "->", "defaultValue", "(", "1", ")", "->", "validate", "(", ")", "->", "ifTrue", "(", "function", "(", "$", "v", ")", "{", "return", "!", "is_numeric", "(", "$", "v", ")", ";", "}", ")", "->", "thenInvalid", "(", "'weight must be numeric'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'timeout'", ")", "->", "defaultValue", "(", "1", ")", "->", "validate", "(", ")", "->", "ifTrue", "(", "function", "(", "$", "v", ")", "{", "return", "!", "is_numeric", "(", "$", "v", ")", ";", "}", ")", "->", "thenInvalid", "(", "'timeout must be numeric'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'retry_interval'", ")", "->", "defaultValue", "(", "15", ")", "->", "validate", "(", ")", "->", "ifTrue", "(", "function", "(", "$", "v", ")", "{", "return", "!", "is_numeric", "(", "$", "v", ")", ";", "}", ")", "->", "thenInvalid", "(", "'retry_interval must be numeric'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "append", "(", "$", "this", "->", "addMemcacheOptionsSection", "(", ")", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", ";", "return", "$", "node", ";", "}" ]
Configure the "lsw_memcache.pools" section @return ArrayNodeDefinition
[ "Configure", "the", "lsw_memcache", ".", "pools", "section" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/DependencyInjection/Configuration.php#L40-L105
37,627
LeaseWeb/LswMemcacheBundle
DependencyInjection/Configuration.php
Configuration.addSessionSupportSection
private function addSessionSupportSection() { $tree = new TreeBuilder(); $node = $tree->root('session'); $node ->children() ->scalarNode('pool')->isRequired()->end() ->booleanNode('auto_load')->defaultTrue()->end() ->scalarNode('prefix')->defaultValue('lmbs')->end() ->scalarNode('ttl')->end() ->booleanNode('locking')->defaultTrue()->end() ->scalarNode('spin_lock_wait')->defaultValue(150000)->end() ->scalarNode('lock_max_wait') ->defaultNull() ->validate() ->always(function($v) { if (null === $v) { return $v; } if (!is_numeric($v)) { throw new InvalidConfigurationException("Option 'lock_max_wait' must either be NULL or an integer value"); } return (int) $v; }) ->end() ->end() ->end(); return $node; }
php
private function addSessionSupportSection() { $tree = new TreeBuilder(); $node = $tree->root('session'); $node ->children() ->scalarNode('pool')->isRequired()->end() ->booleanNode('auto_load')->defaultTrue()->end() ->scalarNode('prefix')->defaultValue('lmbs')->end() ->scalarNode('ttl')->end() ->booleanNode('locking')->defaultTrue()->end() ->scalarNode('spin_lock_wait')->defaultValue(150000)->end() ->scalarNode('lock_max_wait') ->defaultNull() ->validate() ->always(function($v) { if (null === $v) { return $v; } if (!is_numeric($v)) { throw new InvalidConfigurationException("Option 'lock_max_wait' must either be NULL or an integer value"); } return (int) $v; }) ->end() ->end() ->end(); return $node; }
[ "private", "function", "addSessionSupportSection", "(", ")", "{", "$", "tree", "=", "new", "TreeBuilder", "(", ")", ";", "$", "node", "=", "$", "tree", "->", "root", "(", "'session'", ")", ";", "$", "node", "->", "children", "(", ")", "->", "scalarNode", "(", "'pool'", ")", "->", "isRequired", "(", ")", "->", "end", "(", ")", "->", "booleanNode", "(", "'auto_load'", ")", "->", "defaultTrue", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'prefix'", ")", "->", "defaultValue", "(", "'lmbs'", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'ttl'", ")", "->", "end", "(", ")", "->", "booleanNode", "(", "'locking'", ")", "->", "defaultTrue", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'spin_lock_wait'", ")", "->", "defaultValue", "(", "150000", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'lock_max_wait'", ")", "->", "defaultNull", "(", ")", "->", "validate", "(", ")", "->", "always", "(", "function", "(", "$", "v", ")", "{", "if", "(", "null", "===", "$", "v", ")", "{", "return", "$", "v", ";", "}", "if", "(", "!", "is_numeric", "(", "$", "v", ")", ")", "{", "throw", "new", "InvalidConfigurationException", "(", "\"Option 'lock_max_wait' must either be NULL or an integer value\"", ")", ";", "}", "return", "(", "int", ")", "$", "v", ";", "}", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", ";", "return", "$", "node", ";", "}" ]
Configure the "lsw_memcache.session" section @return ArrayNodeDefinition
[ "Configure", "the", "lsw_memcache", ".", "session", "section" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/DependencyInjection/Configuration.php#L112-L144
37,628
LeaseWeb/LswMemcacheBundle
DependencyInjection/Configuration.php
Configuration.addDoctrineSection
private function addDoctrineSection() { $tree = new TreeBuilder(); $node = $tree->root('doctrine'); foreach (array('metadata_cache', 'result_cache', 'query_cache') as $type) { $node->children() ->arrayNode($type) ->canBeUnset() ->children() ->scalarNode('pool')->isRequired()->end() ->scalarNode('prefix')->defaultValue('lmbd')->end() ->end() ->fixXmlConfig('entity_manager') ->children() ->arrayNode('entity_managers') ->defaultValue(array()) ->beforeNormalization()->ifString()->then(function($v) { return (array) $v; })->end() ->prototype('scalar')->end() ->end() ->end() ->fixXmlConfig('document_manager') ->children() ->arrayNode('document_managers') ->defaultValue(array()) ->beforeNormalization()->ifString()->then(function($v) { return (array) $v; })->end() ->prototype('scalar')->end() ->end() ->end() ->end() ->end(); } return $node; }
php
private function addDoctrineSection() { $tree = new TreeBuilder(); $node = $tree->root('doctrine'); foreach (array('metadata_cache', 'result_cache', 'query_cache') as $type) { $node->children() ->arrayNode($type) ->canBeUnset() ->children() ->scalarNode('pool')->isRequired()->end() ->scalarNode('prefix')->defaultValue('lmbd')->end() ->end() ->fixXmlConfig('entity_manager') ->children() ->arrayNode('entity_managers') ->defaultValue(array()) ->beforeNormalization()->ifString()->then(function($v) { return (array) $v; })->end() ->prototype('scalar')->end() ->end() ->end() ->fixXmlConfig('document_manager') ->children() ->arrayNode('document_managers') ->defaultValue(array()) ->beforeNormalization()->ifString()->then(function($v) { return (array) $v; })->end() ->prototype('scalar')->end() ->end() ->end() ->end() ->end(); } return $node; }
[ "private", "function", "addDoctrineSection", "(", ")", "{", "$", "tree", "=", "new", "TreeBuilder", "(", ")", ";", "$", "node", "=", "$", "tree", "->", "root", "(", "'doctrine'", ")", ";", "foreach", "(", "array", "(", "'metadata_cache'", ",", "'result_cache'", ",", "'query_cache'", ")", "as", "$", "type", ")", "{", "$", "node", "->", "children", "(", ")", "->", "arrayNode", "(", "$", "type", ")", "->", "canBeUnset", "(", ")", "->", "children", "(", ")", "->", "scalarNode", "(", "'pool'", ")", "->", "isRequired", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'prefix'", ")", "->", "defaultValue", "(", "'lmbd'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "fixXmlConfig", "(", "'entity_manager'", ")", "->", "children", "(", ")", "->", "arrayNode", "(", "'entity_managers'", ")", "->", "defaultValue", "(", "array", "(", ")", ")", "->", "beforeNormalization", "(", ")", "->", "ifString", "(", ")", "->", "then", "(", "function", "(", "$", "v", ")", "{", "return", "(", "array", ")", "$", "v", ";", "}", ")", "->", "end", "(", ")", "->", "prototype", "(", "'scalar'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "fixXmlConfig", "(", "'document_manager'", ")", "->", "children", "(", ")", "->", "arrayNode", "(", "'document_managers'", ")", "->", "defaultValue", "(", "array", "(", ")", ")", "->", "beforeNormalization", "(", ")", "->", "ifString", "(", ")", "->", "then", "(", "function", "(", "$", "v", ")", "{", "return", "(", "array", ")", "$", "v", ";", "}", ")", "->", "end", "(", ")", "->", "prototype", "(", "'scalar'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", ";", "}", "return", "$", "node", ";", "}" ]
Configure the "lsw_memcache.doctrine" section @return ArrayNodeDefinition
[ "Configure", "the", "lsw_memcache", ".", "doctrine", "section" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/DependencyInjection/Configuration.php#L151-L185
37,629
LeaseWeb/LswMemcacheBundle
DependencyInjection/Configuration.php
Configuration.addFirewallSection
private function addFirewallSection() { $tree = new TreeBuilder(); $node = $tree->root('firewall'); $node ->children() ->scalarNode('pool')->isRequired()->end() ->scalarNode('prefix')->defaultValue('lmbf')->end() ->scalarNode('concurrency') ->defaultValue(10) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('concurrency must be numeric') ->end() ->end() ->scalarNode('spin_lock_wait') ->defaultValue(150000) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('spin_lock_wait must be numeric') ->end() ->end() ->scalarNode('lock_max_wait') ->defaultValue(300) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('lock_max_wait must be numeric') ->end() ->end() ->arrayNode('reverse_proxies') ->defaultValue(array()) ->prototype('scalar')->end() ->end() ->scalarNode('x_forwarded_for')->defaultFalse()->end() ->end() ->end(); return $node; }
php
private function addFirewallSection() { $tree = new TreeBuilder(); $node = $tree->root('firewall'); $node ->children() ->scalarNode('pool')->isRequired()->end() ->scalarNode('prefix')->defaultValue('lmbf')->end() ->scalarNode('concurrency') ->defaultValue(10) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('concurrency must be numeric') ->end() ->end() ->scalarNode('spin_lock_wait') ->defaultValue(150000) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('spin_lock_wait must be numeric') ->end() ->end() ->scalarNode('lock_max_wait') ->defaultValue(300) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('lock_max_wait must be numeric') ->end() ->end() ->arrayNode('reverse_proxies') ->defaultValue(array()) ->prototype('scalar')->end() ->end() ->scalarNode('x_forwarded_for')->defaultFalse()->end() ->end() ->end(); return $node; }
[ "private", "function", "addFirewallSection", "(", ")", "{", "$", "tree", "=", "new", "TreeBuilder", "(", ")", ";", "$", "node", "=", "$", "tree", "->", "root", "(", "'firewall'", ")", ";", "$", "node", "->", "children", "(", ")", "->", "scalarNode", "(", "'pool'", ")", "->", "isRequired", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'prefix'", ")", "->", "defaultValue", "(", "'lmbf'", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'concurrency'", ")", "->", "defaultValue", "(", "10", ")", "->", "validate", "(", ")", "->", "ifTrue", "(", "function", "(", "$", "v", ")", "{", "return", "!", "is_numeric", "(", "$", "v", ")", ";", "}", ")", "->", "thenInvalid", "(", "'concurrency must be numeric'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'spin_lock_wait'", ")", "->", "defaultValue", "(", "150000", ")", "->", "validate", "(", ")", "->", "ifTrue", "(", "function", "(", "$", "v", ")", "{", "return", "!", "is_numeric", "(", "$", "v", ")", ";", "}", ")", "->", "thenInvalid", "(", "'spin_lock_wait must be numeric'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'lock_max_wait'", ")", "->", "defaultValue", "(", "300", ")", "->", "validate", "(", ")", "->", "ifTrue", "(", "function", "(", "$", "v", ")", "{", "return", "!", "is_numeric", "(", "$", "v", ")", ";", "}", ")", "->", "thenInvalid", "(", "'lock_max_wait must be numeric'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "'reverse_proxies'", ")", "->", "defaultValue", "(", "array", "(", ")", ")", "->", "prototype", "(", "'scalar'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'x_forwarded_for'", ")", "->", "defaultFalse", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", ";", "return", "$", "node", ";", "}" ]
Configure the "lsw_memcache.firewall" section @return ArrayNodeDefinition
[ "Configure", "the", "lsw_memcache", ".", "firewall", "section" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/DependencyInjection/Configuration.php#L192-L231
37,630
LeaseWeb/LswMemcacheBundle
DependencyInjection/Configuration.php
Configuration.addMemcacheOptionsSection
private function addMemcacheOptionsSection() { $tree = new TreeBuilder(); $node = $tree->root('options'); // Memcache only configs $node ->addDefaultsIfNotSet() ->children() ->booleanNode('allow_failover')->defaultTrue()->end() ->scalarNode('max_failover_attempts') ->defaultValue(20) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('max_failover_attempts option must be numeric') ->end() ->end() ->scalarNode('default_port') ->defaultValue(11211) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('default_port option must be numeric') ->end() ->end() ->scalarNode('chunk_size') ->defaultValue(32768) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('chunk_size option must be numeric') ->end() ->end() ->scalarNode('protocol') ->defaultValue('ascii') ->validate() ->ifNotInArray(array('ascii', 'binary')) ->thenInvalid('protocol option must be: ascii or binary') ->end() ->end() ->scalarNode('hash_strategy') ->defaultValue('consistent') ->validate() ->ifNotInArray(array('standard', 'consistent')) ->thenInvalid('hash_strategy option must be: standard or consistent') ->end() ->end() ->scalarNode('hash_function') ->defaultValue('crc32') ->validate() ->ifNotInArray(array('crc32', 'fnv')) ->thenInvalid('hash_function option must be: crc32 or fnv') ->end() ->end() ->booleanNode('redundancy')->defaultTrue()->end() ->scalarNode('session_redundancy') ->defaultValue(2) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('session_redundancy option must be numeric') ->end() ->end() ->scalarNode('compress_threshold') ->defaultValue(20000) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('compress_threshold option must be numeric') ->end() ->end() ->scalarNode('lock_timeout') ->defaultValue(15) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('lock_timeout option must be numeric') ->end() ->end() ->end() ->end(); return $node; }
php
private function addMemcacheOptionsSection() { $tree = new TreeBuilder(); $node = $tree->root('options'); // Memcache only configs $node ->addDefaultsIfNotSet() ->children() ->booleanNode('allow_failover')->defaultTrue()->end() ->scalarNode('max_failover_attempts') ->defaultValue(20) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('max_failover_attempts option must be numeric') ->end() ->end() ->scalarNode('default_port') ->defaultValue(11211) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('default_port option must be numeric') ->end() ->end() ->scalarNode('chunk_size') ->defaultValue(32768) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('chunk_size option must be numeric') ->end() ->end() ->scalarNode('protocol') ->defaultValue('ascii') ->validate() ->ifNotInArray(array('ascii', 'binary')) ->thenInvalid('protocol option must be: ascii or binary') ->end() ->end() ->scalarNode('hash_strategy') ->defaultValue('consistent') ->validate() ->ifNotInArray(array('standard', 'consistent')) ->thenInvalid('hash_strategy option must be: standard or consistent') ->end() ->end() ->scalarNode('hash_function') ->defaultValue('crc32') ->validate() ->ifNotInArray(array('crc32', 'fnv')) ->thenInvalid('hash_function option must be: crc32 or fnv') ->end() ->end() ->booleanNode('redundancy')->defaultTrue()->end() ->scalarNode('session_redundancy') ->defaultValue(2) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('session_redundancy option must be numeric') ->end() ->end() ->scalarNode('compress_threshold') ->defaultValue(20000) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('compress_threshold option must be numeric') ->end() ->end() ->scalarNode('lock_timeout') ->defaultValue(15) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('lock_timeout option must be numeric') ->end() ->end() ->end() ->end(); return $node; }
[ "private", "function", "addMemcacheOptionsSection", "(", ")", "{", "$", "tree", "=", "new", "TreeBuilder", "(", ")", ";", "$", "node", "=", "$", "tree", "->", "root", "(", "'options'", ")", ";", "// Memcache only configs", "$", "node", "->", "addDefaultsIfNotSet", "(", ")", "->", "children", "(", ")", "->", "booleanNode", "(", "'allow_failover'", ")", "->", "defaultTrue", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'max_failover_attempts'", ")", "->", "defaultValue", "(", "20", ")", "->", "validate", "(", ")", "->", "ifTrue", "(", "function", "(", "$", "v", ")", "{", "return", "!", "is_numeric", "(", "$", "v", ")", ";", "}", ")", "->", "thenInvalid", "(", "'max_failover_attempts option must be numeric'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'default_port'", ")", "->", "defaultValue", "(", "11211", ")", "->", "validate", "(", ")", "->", "ifTrue", "(", "function", "(", "$", "v", ")", "{", "return", "!", "is_numeric", "(", "$", "v", ")", ";", "}", ")", "->", "thenInvalid", "(", "'default_port option must be numeric'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'chunk_size'", ")", "->", "defaultValue", "(", "32768", ")", "->", "validate", "(", ")", "->", "ifTrue", "(", "function", "(", "$", "v", ")", "{", "return", "!", "is_numeric", "(", "$", "v", ")", ";", "}", ")", "->", "thenInvalid", "(", "'chunk_size option must be numeric'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'protocol'", ")", "->", "defaultValue", "(", "'ascii'", ")", "->", "validate", "(", ")", "->", "ifNotInArray", "(", "array", "(", "'ascii'", ",", "'binary'", ")", ")", "->", "thenInvalid", "(", "'protocol option must be: ascii or binary'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'hash_strategy'", ")", "->", "defaultValue", "(", "'consistent'", ")", "->", "validate", "(", ")", "->", "ifNotInArray", "(", "array", "(", "'standard'", ",", "'consistent'", ")", ")", "->", "thenInvalid", "(", "'hash_strategy option must be: standard or consistent'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'hash_function'", ")", "->", "defaultValue", "(", "'crc32'", ")", "->", "validate", "(", ")", "->", "ifNotInArray", "(", "array", "(", "'crc32'", ",", "'fnv'", ")", ")", "->", "thenInvalid", "(", "'hash_function option must be: crc32 or fnv'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "booleanNode", "(", "'redundancy'", ")", "->", "defaultTrue", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'session_redundancy'", ")", "->", "defaultValue", "(", "2", ")", "->", "validate", "(", ")", "->", "ifTrue", "(", "function", "(", "$", "v", ")", "{", "return", "!", "is_numeric", "(", "$", "v", ")", ";", "}", ")", "->", "thenInvalid", "(", "'session_redundancy option must be numeric'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'compress_threshold'", ")", "->", "defaultValue", "(", "20000", ")", "->", "validate", "(", ")", "->", "ifTrue", "(", "function", "(", "$", "v", ")", "{", "return", "!", "is_numeric", "(", "$", "v", ")", ";", "}", ")", "->", "thenInvalid", "(", "'compress_threshold option must be numeric'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'lock_timeout'", ")", "->", "defaultValue", "(", "15", ")", "->", "validate", "(", ")", "->", "ifTrue", "(", "function", "(", "$", "v", ")", "{", "return", "!", "is_numeric", "(", "$", "v", ")", ";", "}", ")", "->", "thenInvalid", "(", "'lock_timeout option must be numeric'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", ";", "return", "$", "node", ";", "}" ]
Configure the "lsw_memcache.options" section @return ArrayNodeDefinition
[ "Configure", "the", "lsw_memcache", ".", "options", "section" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/DependencyInjection/Configuration.php#L238-L317
37,631
LeaseWeb/LswMemcacheBundle
Command/ClearCommand.php
ClearCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $pool = $input->getArgument('pool'); try { $this->memcache = $this->getContainer()->get('memcache.'.$pool); $output->writeln($this->memcache->flush()?'<info>OK</info>':'<error>ERROR</error>'); } catch (ServiceNotFoundException $e) { $output->writeln("<error>pool '$pool' is not found</error>"); } }
php
protected function execute(InputInterface $input, OutputInterface $output) { $pool = $input->getArgument('pool'); try { $this->memcache = $this->getContainer()->get('memcache.'.$pool); $output->writeln($this->memcache->flush()?'<info>OK</info>':'<error>ERROR</error>'); } catch (ServiceNotFoundException $e) { $output->writeln("<error>pool '$pool' is not found</error>"); } }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "pool", "=", "$", "input", "->", "getArgument", "(", "'pool'", ")", ";", "try", "{", "$", "this", "->", "memcache", "=", "$", "this", "->", "getContainer", "(", ")", "->", "get", "(", "'memcache.'", ".", "$", "pool", ")", ";", "$", "output", "->", "writeln", "(", "$", "this", "->", "memcache", "->", "flush", "(", ")", "?", "'<info>OK</info>'", ":", "'<error>ERROR</error>'", ")", ";", "}", "catch", "(", "ServiceNotFoundException", "$", "e", ")", "{", "$", "output", "->", "writeln", "(", "\"<error>pool '$pool' is not found</error>\"", ")", ";", "}", "}" ]
Execute the CLI task @param InputInterface $input Command input @param OutputInterface $output Command output @return void
[ "Execute", "the", "CLI", "task" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/Command/ClearCommand.php#L46-L57
37,632
LeaseWeb/LswMemcacheBundle
DependencyInjection/LswMemcacheExtension.php
LswMemcacheExtension.enableSessionSupport
private function enableSessionSupport($config, ContainerBuilder $container) { // make sure the pool is specified and it exists $pool = $config['session']['pool']; if (null === $pool) { return; } if (!isset($config['pools']) || !isset($config['pools'][$pool])) { throw new \LogicException(sprintf('The pool "%s" does not exist! Cannot enable the session support!', $pool)); } // calculate options $sessionOptions = $container->getParameter('session.storage.options'); $options = array(); if (isset($config['session']['ttl'])) { $options['expiretime'] = $config['session']['ttl']; } elseif (isset($sessionOptions['cookie_lifetime'])) { $options['expiretime'] = $sessionOptions['cookie_lifetime']; } $options['prefix'] = $config['session']['prefix']; $options['locking'] = $config['session']['locking']; $options['spin_lock_wait'] = $config['session']['spin_lock_wait']; $options['lock_max_wait'] = $config['session']['lock_max_wait']; // set the auto_load parameter $container->setParameter('memcache.session_handler.auto_load', $config['session']['auto_load']); // load the session handler $definition = new Definition($container->getParameter('memcache.session_handler.class')); $container->setDefinition('memcache.session_handler', $definition); $definition ->addArgument(new Reference(sprintf('memcache.%s', $pool))) ->addArgument($options); $this->addClassesToCompile(array($definition->getClass())); }
php
private function enableSessionSupport($config, ContainerBuilder $container) { // make sure the pool is specified and it exists $pool = $config['session']['pool']; if (null === $pool) { return; } if (!isset($config['pools']) || !isset($config['pools'][$pool])) { throw new \LogicException(sprintf('The pool "%s" does not exist! Cannot enable the session support!', $pool)); } // calculate options $sessionOptions = $container->getParameter('session.storage.options'); $options = array(); if (isset($config['session']['ttl'])) { $options['expiretime'] = $config['session']['ttl']; } elseif (isset($sessionOptions['cookie_lifetime'])) { $options['expiretime'] = $sessionOptions['cookie_lifetime']; } $options['prefix'] = $config['session']['prefix']; $options['locking'] = $config['session']['locking']; $options['spin_lock_wait'] = $config['session']['spin_lock_wait']; $options['lock_max_wait'] = $config['session']['lock_max_wait']; // set the auto_load parameter $container->setParameter('memcache.session_handler.auto_load', $config['session']['auto_load']); // load the session handler $definition = new Definition($container->getParameter('memcache.session_handler.class')); $container->setDefinition('memcache.session_handler', $definition); $definition ->addArgument(new Reference(sprintf('memcache.%s', $pool))) ->addArgument($options); $this->addClassesToCompile(array($definition->getClass())); }
[ "private", "function", "enableSessionSupport", "(", "$", "config", ",", "ContainerBuilder", "$", "container", ")", "{", "// make sure the pool is specified and it exists", "$", "pool", "=", "$", "config", "[", "'session'", "]", "[", "'pool'", "]", ";", "if", "(", "null", "===", "$", "pool", ")", "{", "return", ";", "}", "if", "(", "!", "isset", "(", "$", "config", "[", "'pools'", "]", ")", "||", "!", "isset", "(", "$", "config", "[", "'pools'", "]", "[", "$", "pool", "]", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'The pool \"%s\" does not exist! Cannot enable the session support!'", ",", "$", "pool", ")", ")", ";", "}", "// calculate options", "$", "sessionOptions", "=", "$", "container", "->", "getParameter", "(", "'session.storage.options'", ")", ";", "$", "options", "=", "array", "(", ")", ";", "if", "(", "isset", "(", "$", "config", "[", "'session'", "]", "[", "'ttl'", "]", ")", ")", "{", "$", "options", "[", "'expiretime'", "]", "=", "$", "config", "[", "'session'", "]", "[", "'ttl'", "]", ";", "}", "elseif", "(", "isset", "(", "$", "sessionOptions", "[", "'cookie_lifetime'", "]", ")", ")", "{", "$", "options", "[", "'expiretime'", "]", "=", "$", "sessionOptions", "[", "'cookie_lifetime'", "]", ";", "}", "$", "options", "[", "'prefix'", "]", "=", "$", "config", "[", "'session'", "]", "[", "'prefix'", "]", ";", "$", "options", "[", "'locking'", "]", "=", "$", "config", "[", "'session'", "]", "[", "'locking'", "]", ";", "$", "options", "[", "'spin_lock_wait'", "]", "=", "$", "config", "[", "'session'", "]", "[", "'spin_lock_wait'", "]", ";", "$", "options", "[", "'lock_max_wait'", "]", "=", "$", "config", "[", "'session'", "]", "[", "'lock_max_wait'", "]", ";", "// set the auto_load parameter", "$", "container", "->", "setParameter", "(", "'memcache.session_handler.auto_load'", ",", "$", "config", "[", "'session'", "]", "[", "'auto_load'", "]", ")", ";", "// load the session handler", "$", "definition", "=", "new", "Definition", "(", "$", "container", "->", "getParameter", "(", "'memcache.session_handler.class'", ")", ")", ";", "$", "container", "->", "setDefinition", "(", "'memcache.session_handler'", ",", "$", "definition", ")", ";", "$", "definition", "->", "addArgument", "(", "new", "Reference", "(", "sprintf", "(", "'memcache.%s'", ",", "$", "pool", ")", ")", ")", "->", "addArgument", "(", "$", "options", ")", ";", "$", "this", "->", "addClassesToCompile", "(", "array", "(", "$", "definition", "->", "getClass", "(", ")", ")", ")", ";", "}" ]
Enables session support using Memcache based on the configuration @param string $config Configuration for bundle @param ContainerBuilder $container Service container @return void
[ "Enables", "session", "support", "using", "Memcache", "based", "on", "the", "configuration" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/DependencyInjection/LswMemcacheExtension.php#L58-L89
37,633
LeaseWeb/LswMemcacheBundle
DependencyInjection/LswMemcacheExtension.php
LswMemcacheExtension.loadFirewall
protected function loadFirewall(array $config, ContainerBuilder $container) { // make sure the pool is specified and it exists $pool = $config['firewall']['pool']; if (null === $pool) { return; } if (!isset($config['pools']) || !isset($config['pools'][$pool])) { throw new \LogicException(sprintf('The pool "%s" does not exist! Cannot enable the firewall!', $pool)); } // calculate options $options = array(); $options['prefix'] = $config['firewall']['prefix']; $options['concurrency'] = $config['firewall']['concurrency']; $options['spin_lock_wait'] = $config['firewall']['spin_lock_wait']; $options['lock_max_wait'] = $config['firewall']['lock_max_wait']; $options['reverse_proxies'] = $config['firewall']['reverse_proxies']; $options['x_forwarded_for'] = $config['firewall']['x_forwarded_for']; // load the firewall handler $definition = new Definition($container->getParameter('memcache.firewall_handler.class')); $container->setDefinition('memcache.firewall_handler', $definition); $definition ->addArgument(new Reference(sprintf('memcache.%s', $pool))) ->addArgument($options); $definition->addTag('kernel.event_listener', array('event'=>'kernel.request','method'=>'onKernelRequest')); $definition->addTag('kernel.event_listener', array('event'=>'kernel.terminate','method'=>'onKernelTerminate')); $this->addClassesToCompile(array($definition->getClass())); }
php
protected function loadFirewall(array $config, ContainerBuilder $container) { // make sure the pool is specified and it exists $pool = $config['firewall']['pool']; if (null === $pool) { return; } if (!isset($config['pools']) || !isset($config['pools'][$pool])) { throw new \LogicException(sprintf('The pool "%s" does not exist! Cannot enable the firewall!', $pool)); } // calculate options $options = array(); $options['prefix'] = $config['firewall']['prefix']; $options['concurrency'] = $config['firewall']['concurrency']; $options['spin_lock_wait'] = $config['firewall']['spin_lock_wait']; $options['lock_max_wait'] = $config['firewall']['lock_max_wait']; $options['reverse_proxies'] = $config['firewall']['reverse_proxies']; $options['x_forwarded_for'] = $config['firewall']['x_forwarded_for']; // load the firewall handler $definition = new Definition($container->getParameter('memcache.firewall_handler.class')); $container->setDefinition('memcache.firewall_handler', $definition); $definition ->addArgument(new Reference(sprintf('memcache.%s', $pool))) ->addArgument($options); $definition->addTag('kernel.event_listener', array('event'=>'kernel.request','method'=>'onKernelRequest')); $definition->addTag('kernel.event_listener', array('event'=>'kernel.terminate','method'=>'onKernelTerminate')); $this->addClassesToCompile(array($definition->getClass())); }
[ "protected", "function", "loadFirewall", "(", "array", "$", "config", ",", "ContainerBuilder", "$", "container", ")", "{", "// make sure the pool is specified and it exists", "$", "pool", "=", "$", "config", "[", "'firewall'", "]", "[", "'pool'", "]", ";", "if", "(", "null", "===", "$", "pool", ")", "{", "return", ";", "}", "if", "(", "!", "isset", "(", "$", "config", "[", "'pools'", "]", ")", "||", "!", "isset", "(", "$", "config", "[", "'pools'", "]", "[", "$", "pool", "]", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'The pool \"%s\" does not exist! Cannot enable the firewall!'", ",", "$", "pool", ")", ")", ";", "}", "// calculate options", "$", "options", "=", "array", "(", ")", ";", "$", "options", "[", "'prefix'", "]", "=", "$", "config", "[", "'firewall'", "]", "[", "'prefix'", "]", ";", "$", "options", "[", "'concurrency'", "]", "=", "$", "config", "[", "'firewall'", "]", "[", "'concurrency'", "]", ";", "$", "options", "[", "'spin_lock_wait'", "]", "=", "$", "config", "[", "'firewall'", "]", "[", "'spin_lock_wait'", "]", ";", "$", "options", "[", "'lock_max_wait'", "]", "=", "$", "config", "[", "'firewall'", "]", "[", "'lock_max_wait'", "]", ";", "$", "options", "[", "'reverse_proxies'", "]", "=", "$", "config", "[", "'firewall'", "]", "[", "'reverse_proxies'", "]", ";", "$", "options", "[", "'x_forwarded_for'", "]", "=", "$", "config", "[", "'firewall'", "]", "[", "'x_forwarded_for'", "]", ";", "// load the firewall handler", "$", "definition", "=", "new", "Definition", "(", "$", "container", "->", "getParameter", "(", "'memcache.firewall_handler.class'", ")", ")", ";", "$", "container", "->", "setDefinition", "(", "'memcache.firewall_handler'", ",", "$", "definition", ")", ";", "$", "definition", "->", "addArgument", "(", "new", "Reference", "(", "sprintf", "(", "'memcache.%s'", ",", "$", "pool", ")", ")", ")", "->", "addArgument", "(", "$", "options", ")", ";", "$", "definition", "->", "addTag", "(", "'kernel.event_listener'", ",", "array", "(", "'event'", "=>", "'kernel.request'", ",", "'method'", "=>", "'onKernelRequest'", ")", ")", ";", "$", "definition", "->", "addTag", "(", "'kernel.event_listener'", ",", "array", "(", "'event'", "=>", "'kernel.terminate'", ",", "'method'", "=>", "'onKernelTerminate'", ")", ")", ";", "$", "this", "->", "addClassesToCompile", "(", "array", "(", "$", "definition", "->", "getClass", "(", ")", ")", ")", ";", "}" ]
Loads the Firewall configuration. @param array $config A configuration array @param ContainerBuilder $container A ContainerBuilder instance
[ "Loads", "the", "Firewall", "configuration", "." ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/DependencyInjection/LswMemcacheExtension.php#L136-L163
37,634
LeaseWeb/LswMemcacheBundle
DependencyInjection/LswMemcacheExtension.php
LswMemcacheExtension.newMemcacheClient
private function newMemcacheClient($name, array $config, ContainerBuilder $container) { // Check if the Memcache extension is loaded if (!extension_loaded('memcache')) { throw new \LogicException('Memcache extension is not loaded! To configure pools it MUST be loaded!'); } $memcache = new Definition('Lsw\MemcacheBundle\Cache\AntiDogPileMemcache'); $memcache->addArgument(new Parameter('kernel.debug')); // Add servers to the memcache pool foreach ($config['servers'] as $s) { $server = array( $s['host'], $s['tcp_port'], $s['udp_port'], $s['persistent'], $s['weight'], $s['timeout'], $s['retry_interval'] ); if ($s['host']) { $memcache->addMethodCall('addServer', $server); } } $memcache->addArgument($config['options']); $options = array(); // Make sure that config values are human readable foreach ($config['options'] as $key => $value) { $options[$key] = var_export($value, true); } // Add the service to the container $serviceName = sprintf('memcache.%s', $name); $container->setDefinition($serviceName, $memcache); // Add the service to the data collector if ($container->hasDefinition('memcache.data_collector')) { $definition = $container->getDefinition('memcache.data_collector'); $definition->addMethodCall('addClient', array($name, $options, new Reference($serviceName))); } }
php
private function newMemcacheClient($name, array $config, ContainerBuilder $container) { // Check if the Memcache extension is loaded if (!extension_loaded('memcache')) { throw new \LogicException('Memcache extension is not loaded! To configure pools it MUST be loaded!'); } $memcache = new Definition('Lsw\MemcacheBundle\Cache\AntiDogPileMemcache'); $memcache->addArgument(new Parameter('kernel.debug')); // Add servers to the memcache pool foreach ($config['servers'] as $s) { $server = array( $s['host'], $s['tcp_port'], $s['udp_port'], $s['persistent'], $s['weight'], $s['timeout'], $s['retry_interval'] ); if ($s['host']) { $memcache->addMethodCall('addServer', $server); } } $memcache->addArgument($config['options']); $options = array(); // Make sure that config values are human readable foreach ($config['options'] as $key => $value) { $options[$key] = var_export($value, true); } // Add the service to the container $serviceName = sprintf('memcache.%s', $name); $container->setDefinition($serviceName, $memcache); // Add the service to the data collector if ($container->hasDefinition('memcache.data_collector')) { $definition = $container->getDefinition('memcache.data_collector'); $definition->addMethodCall('addClient', array($name, $options, new Reference($serviceName))); } }
[ "private", "function", "newMemcacheClient", "(", "$", "name", ",", "array", "$", "config", ",", "ContainerBuilder", "$", "container", ")", "{", "// Check if the Memcache extension is loaded", "if", "(", "!", "extension_loaded", "(", "'memcache'", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "'Memcache extension is not loaded! To configure pools it MUST be loaded!'", ")", ";", "}", "$", "memcache", "=", "new", "Definition", "(", "'Lsw\\MemcacheBundle\\Cache\\AntiDogPileMemcache'", ")", ";", "$", "memcache", "->", "addArgument", "(", "new", "Parameter", "(", "'kernel.debug'", ")", ")", ";", "// Add servers to the memcache pool", "foreach", "(", "$", "config", "[", "'servers'", "]", "as", "$", "s", ")", "{", "$", "server", "=", "array", "(", "$", "s", "[", "'host'", "]", ",", "$", "s", "[", "'tcp_port'", "]", ",", "$", "s", "[", "'udp_port'", "]", ",", "$", "s", "[", "'persistent'", "]", ",", "$", "s", "[", "'weight'", "]", ",", "$", "s", "[", "'timeout'", "]", ",", "$", "s", "[", "'retry_interval'", "]", ")", ";", "if", "(", "$", "s", "[", "'host'", "]", ")", "{", "$", "memcache", "->", "addMethodCall", "(", "'addServer'", ",", "$", "server", ")", ";", "}", "}", "$", "memcache", "->", "addArgument", "(", "$", "config", "[", "'options'", "]", ")", ";", "$", "options", "=", "array", "(", ")", ";", "// Make sure that config values are human readable", "foreach", "(", "$", "config", "[", "'options'", "]", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "options", "[", "$", "key", "]", "=", "var_export", "(", "$", "value", ",", "true", ")", ";", "}", "// Add the service to the container", "$", "serviceName", "=", "sprintf", "(", "'memcache.%s'", ",", "$", "name", ")", ";", "$", "container", "->", "setDefinition", "(", "$", "serviceName", ",", "$", "memcache", ")", ";", "// Add the service to the data collector", "if", "(", "$", "container", "->", "hasDefinition", "(", "'memcache.data_collector'", ")", ")", "{", "$", "definition", "=", "$", "container", "->", "getDefinition", "(", "'memcache.data_collector'", ")", ";", "$", "definition", "->", "addMethodCall", "(", "'addClient'", ",", "array", "(", "$", "name", ",", "$", "options", ",", "new", "Reference", "(", "$", "serviceName", ")", ")", ")", ";", "}", "}" ]
Creates a new Memcache definition @param string $name Client name @param array $config Client configuration @param ContainerBuilder $container Service container @throws \LogicException
[ "Creates", "a", "new", "Memcache", "definition" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/DependencyInjection/LswMemcacheExtension.php#L189-L231
37,635
LeaseWeb/LswMemcacheBundle
DataCollector/MemcacheDataCollector.php
MemcacheDataCollector.addClient
public function addClient($name, $options, LoggingMemcacheInterface $memcache) { $this->pools[$name] = $memcache; $this->options[$name] = $options; }
php
public function addClient($name, $options, LoggingMemcacheInterface $memcache) { $this->pools[$name] = $memcache; $this->options[$name] = $options; }
[ "public", "function", "addClient", "(", "$", "name", ",", "$", "options", ",", "LoggingMemcacheInterface", "$", "memcache", ")", "{", "$", "this", "->", "pools", "[", "$", "name", "]", "=", "$", "memcache", ";", "$", "this", "->", "options", "[", "$", "name", "]", "=", "$", "options", ";", "}" ]
Add a Memcache object to the collector @param string $name Name of the Memcache pool @param array $options Options for Memcache pool @param LoggingMemcacheInterface $memcache Logging Memcache object @return void
[ "Add", "a", "Memcache", "object", "to", "the", "collector" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/DataCollector/MemcacheDataCollector.php#L40-L44
37,636
geerlingguy/Request
JJG/Request.php
Request.checkResponseForContent
public function checkResponseForContent($content = '') { if ($this->httpCode == 200 && !empty($this->responseBody)) { if (strpos($this->responseBody, $content) !== FALSE) { return TRUE; } } return FALSE; }
php
public function checkResponseForContent($content = '') { if ($this->httpCode == 200 && !empty($this->responseBody)) { if (strpos($this->responseBody, $content) !== FALSE) { return TRUE; } } return FALSE; }
[ "public", "function", "checkResponseForContent", "(", "$", "content", "=", "''", ")", "{", "if", "(", "$", "this", "->", "httpCode", "==", "200", "&&", "!", "empty", "(", "$", "this", "->", "responseBody", ")", ")", "{", "if", "(", "strpos", "(", "$", "this", "->", "responseBody", ",", "$", "content", ")", "!==", "FALSE", ")", "{", "return", "TRUE", ";", "}", "}", "return", "FALSE", ";", "}" ]
Check for content in the HTTP response body. This method should not be called until after execute(), and will only check for the content if the response code is 200 OK. @param string $content String for which the response will be checked. @return bool TRUE if $content was found in the response, FALSE otherwise.
[ "Check", "for", "content", "in", "the", "HTTP", "response", "body", "." ]
16d33dd56f2332fe259f6acfd0bdc2bb571738f2
https://github.com/geerlingguy/Request/blob/16d33dd56f2332fe259f6acfd0bdc2bb571738f2/JJG/Request.php#L249-L256
37,637
geerlingguy/Request
JJG/Request.php
Request.execute
public function execute() { // Set a default latency value. $latency = 0; // Set up cURL options. $ch = curl_init(); // If there are basic authentication credentials, use them. if (isset($this->userpwd)) { curl_setopt($ch, CURLOPT_USERPWD, $this->userpwd); } // If cookies are enabled, use them. if ($this->cookiesEnabled) { curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookiePath); curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookiePath); } // Send a custom request if set (instead of standard GET). if (isset($this->requestType)) { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->requestType); // If POST fields are given, and this is a POST request, add fields. if ($this->requestType == 'POST' && isset($this->postFields)) { curl_setopt($ch, CURLOPT_POSTFIELDS, $this->postFields); } } // Don't print the response; return it from curl_exec(). curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_URL, $this->address); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout); curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); // Follow redirects (maximum of 5). curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_MAXREDIRS, 5); // SSL support. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->ssl); // Set a custom UA string so people can identify our requests. curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent); // Output the header in the response. curl_setopt($ch, CURLOPT_HEADER, TRUE); $response = curl_exec($ch); $error = curl_error($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $time = curl_getinfo($ch, CURLINFO_TOTAL_TIME); curl_close($ch); // Set the header, response, error and http code. $this->responseHeader = substr($response, 0, $header_size); $this->responseBody = substr($response, $header_size); $this->error = $error; $this->httpCode = $http_code; // Convert the latency to ms. $this->latency = round($time * 1000); }
php
public function execute() { // Set a default latency value. $latency = 0; // Set up cURL options. $ch = curl_init(); // If there are basic authentication credentials, use them. if (isset($this->userpwd)) { curl_setopt($ch, CURLOPT_USERPWD, $this->userpwd); } // If cookies are enabled, use them. if ($this->cookiesEnabled) { curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookiePath); curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookiePath); } // Send a custom request if set (instead of standard GET). if (isset($this->requestType)) { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->requestType); // If POST fields are given, and this is a POST request, add fields. if ($this->requestType == 'POST' && isset($this->postFields)) { curl_setopt($ch, CURLOPT_POSTFIELDS, $this->postFields); } } // Don't print the response; return it from curl_exec(). curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_URL, $this->address); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout); curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); // Follow redirects (maximum of 5). curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_MAXREDIRS, 5); // SSL support. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->ssl); // Set a custom UA string so people can identify our requests. curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent); // Output the header in the response. curl_setopt($ch, CURLOPT_HEADER, TRUE); $response = curl_exec($ch); $error = curl_error($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $time = curl_getinfo($ch, CURLINFO_TOTAL_TIME); curl_close($ch); // Set the header, response, error and http code. $this->responseHeader = substr($response, 0, $header_size); $this->responseBody = substr($response, $header_size); $this->error = $error; $this->httpCode = $http_code; // Convert the latency to ms. $this->latency = round($time * 1000); }
[ "public", "function", "execute", "(", ")", "{", "// Set a default latency value.", "$", "latency", "=", "0", ";", "// Set up cURL options.", "$", "ch", "=", "curl_init", "(", ")", ";", "// If there are basic authentication credentials, use them.", "if", "(", "isset", "(", "$", "this", "->", "userpwd", ")", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_USERPWD", ",", "$", "this", "->", "userpwd", ")", ";", "}", "// If cookies are enabled, use them.", "if", "(", "$", "this", "->", "cookiesEnabled", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_COOKIEJAR", ",", "$", "this", "->", "cookiePath", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_COOKIEFILE", ",", "$", "this", "->", "cookiePath", ")", ";", "}", "// Send a custom request if set (instead of standard GET).", "if", "(", "isset", "(", "$", "this", "->", "requestType", ")", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_CUSTOMREQUEST", ",", "$", "this", "->", "requestType", ")", ";", "// If POST fields are given, and this is a POST request, add fields.", "if", "(", "$", "this", "->", "requestType", "==", "'POST'", "&&", "isset", "(", "$", "this", "->", "postFields", ")", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POSTFIELDS", ",", "$", "this", "->", "postFields", ")", ";", "}", "}", "// Don't print the response; return it from curl_exec().", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "TRUE", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_URL", ",", "$", "this", "->", "address", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_CONNECTTIMEOUT", ",", "$", "this", "->", "connectTimeout", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_TIMEOUT", ",", "$", "this", "->", "timeout", ")", ";", "// Follow redirects (maximum of 5).", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_FOLLOWLOCATION", ",", "TRUE", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_MAXREDIRS", ",", "5", ")", ";", "// SSL support.", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSL_VERIFYPEER", ",", "$", "this", "->", "ssl", ")", ";", "// Set a custom UA string so people can identify our requests.", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_USERAGENT", ",", "$", "this", "->", "userAgent", ")", ";", "// Output the header in the response.", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HEADER", ",", "TRUE", ")", ";", "$", "response", "=", "curl_exec", "(", "$", "ch", ")", ";", "$", "error", "=", "curl_error", "(", "$", "ch", ")", ";", "$", "http_code", "=", "curl_getinfo", "(", "$", "ch", ",", "CURLINFO_HTTP_CODE", ")", ";", "$", "header_size", "=", "curl_getinfo", "(", "$", "ch", ",", "CURLINFO_HEADER_SIZE", ")", ";", "$", "time", "=", "curl_getinfo", "(", "$", "ch", ",", "CURLINFO_TOTAL_TIME", ")", ";", "curl_close", "(", "$", "ch", ")", ";", "// Set the header, response, error and http code.", "$", "this", "->", "responseHeader", "=", "substr", "(", "$", "response", ",", "0", ",", "$", "header_size", ")", ";", "$", "this", "->", "responseBody", "=", "substr", "(", "$", "response", ",", "$", "header_size", ")", ";", "$", "this", "->", "error", "=", "$", "error", ";", "$", "this", "->", "httpCode", "=", "$", "http_code", ";", "// Convert the latency to ms.", "$", "this", "->", "latency", "=", "round", "(", "$", "time", "*", "1000", ")", ";", "}" ]
Check a given address with cURL. After this method is completed, the response body, headers, latency, etc. will be populated, and can be accessed with the appropriate methods.
[ "Check", "a", "given", "address", "with", "cURL", "." ]
16d33dd56f2332fe259f6acfd0bdc2bb571738f2
https://github.com/geerlingguy/Request/blob/16d33dd56f2332fe259f6acfd0bdc2bb571738f2/JJG/Request.php#L264-L316
37,638
deltaaskii/lara-pdf-merger
src/LynX39/LaraPdfMerger/tcpdf/tcpdf_import.php
TCPDF_IMPORT.importPDF
public function importPDF($filename) { // load document $rawdata = file_get_contents($filename); if ($rawdata === false) { $this->Error('Unable to get the content of the file: '.$filename); } // configuration parameters for parser $cfg = array( 'die_for_errors' => false, 'ignore_filter_decoding_errors' => true, 'ignore_missing_filter_decoders' => true, ); try { // parse PDF data $pdf = new TCPDF_PARSER($rawdata, $cfg); } catch (Exception $e) { die($e->getMessage()); } // get the parsed data $data = $pdf->getParsedData(); // release some memory unset($rawdata); // ... print_r($data); // DEBUG unset($pdf); }
php
public function importPDF($filename) { // load document $rawdata = file_get_contents($filename); if ($rawdata === false) { $this->Error('Unable to get the content of the file: '.$filename); } // configuration parameters for parser $cfg = array( 'die_for_errors' => false, 'ignore_filter_decoding_errors' => true, 'ignore_missing_filter_decoders' => true, ); try { // parse PDF data $pdf = new TCPDF_PARSER($rawdata, $cfg); } catch (Exception $e) { die($e->getMessage()); } // get the parsed data $data = $pdf->getParsedData(); // release some memory unset($rawdata); // ... print_r($data); // DEBUG unset($pdf); }
[ "public", "function", "importPDF", "(", "$", "filename", ")", "{", "// load document", "$", "rawdata", "=", "file_get_contents", "(", "$", "filename", ")", ";", "if", "(", "$", "rawdata", "===", "false", ")", "{", "$", "this", "->", "Error", "(", "'Unable to get the content of the file: '", ".", "$", "filename", ")", ";", "}", "// configuration parameters for parser", "$", "cfg", "=", "array", "(", "'die_for_errors'", "=>", "false", ",", "'ignore_filter_decoding_errors'", "=>", "true", ",", "'ignore_missing_filter_decoders'", "=>", "true", ",", ")", ";", "try", "{", "// parse PDF data", "$", "pdf", "=", "new", "TCPDF_PARSER", "(", "$", "rawdata", ",", "$", "cfg", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "die", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "// get the parsed data", "$", "data", "=", "$", "pdf", "->", "getParsedData", "(", ")", ";", "// release some memory", "unset", "(", "$", "rawdata", ")", ";", "// ...", "print_r", "(", "$", "data", ")", ";", "// DEBUG", "unset", "(", "$", "pdf", ")", ";", "}" ]
Import an existing PDF document @param $filename (string) Filename of the PDF document to import. @return true in case of success, false otherwise @public @since 1.0.000 (2011-05-24)
[ "Import", "an", "existing", "PDF", "document" ]
8cede29130ba6b60d33481b4067a8cba24c21753
https://github.com/deltaaskii/lara-pdf-merger/blob/8cede29130ba6b60d33481b4067a8cba24c21753/src/LynX39/LaraPdfMerger/tcpdf/tcpdf_import.php#L68-L98
37,639
deltaaskii/lara-pdf-merger
src/LynX39/LaraPdfMerger/tcpdf/tcpdi_parser.php
tcpdi_parser.cleanUp
public function cleanUp() { unset($this->pdfdata); $this->pdfdata = ''; unset($this->objstreams); $this->objstreams = array(); unset($this->objects); $this->objects = array(); unset($this->objstreamobjs); $this->objstreamobjs = array(); unset($this->xref); $this->xref = array(); unset($this->objoffsets); $this->objoffsets = array(); unset($this->pages); $this->pages = array(); }
php
public function cleanUp() { unset($this->pdfdata); $this->pdfdata = ''; unset($this->objstreams); $this->objstreams = array(); unset($this->objects); $this->objects = array(); unset($this->objstreamobjs); $this->objstreamobjs = array(); unset($this->xref); $this->xref = array(); unset($this->objoffsets); $this->objoffsets = array(); unset($this->pages); $this->pages = array(); }
[ "public", "function", "cleanUp", "(", ")", "{", "unset", "(", "$", "this", "->", "pdfdata", ")", ";", "$", "this", "->", "pdfdata", "=", "''", ";", "unset", "(", "$", "this", "->", "objstreams", ")", ";", "$", "this", "->", "objstreams", "=", "array", "(", ")", ";", "unset", "(", "$", "this", "->", "objects", ")", ";", "$", "this", "->", "objects", "=", "array", "(", ")", ";", "unset", "(", "$", "this", "->", "objstreamobjs", ")", ";", "$", "this", "->", "objstreamobjs", "=", "array", "(", ")", ";", "unset", "(", "$", "this", "->", "xref", ")", ";", "$", "this", "->", "xref", "=", "array", "(", ")", ";", "unset", "(", "$", "this", "->", "objoffsets", ")", ";", "$", "this", "->", "objoffsets", "=", "array", "(", ")", ";", "unset", "(", "$", "this", "->", "pages", ")", ";", "$", "this", "->", "pages", "=", "array", "(", ")", ";", "}" ]
Clean up when done, to free memory etc
[ "Clean", "up", "when", "done", "to", "free", "memory", "etc" ]
8cede29130ba6b60d33481b4067a8cba24c21753
https://github.com/deltaaskii/lara-pdf-merger/blob/8cede29130ba6b60d33481b4067a8cba24c21753/src/LynX39/LaraPdfMerger/tcpdf/tcpdi_parser.php#L212-L227
37,640
deltaaskii/lara-pdf-merger
src/LynX39/LaraPdfMerger/tcpdf/tcpdi_parser.php
tcpdi_parser.getPDFVersion
public function getPDFVersion() { preg_match('/\d\.\d/', substr($this->pdfdata, 0, 16), $m); if (isset($m[0])) $this->pdfVersion = $m[0]; return $this->pdfVersion; }
php
public function getPDFVersion() { preg_match('/\d\.\d/', substr($this->pdfdata, 0, 16), $m); if (isset($m[0])) $this->pdfVersion = $m[0]; return $this->pdfVersion; }
[ "public", "function", "getPDFVersion", "(", ")", "{", "preg_match", "(", "'/\\d\\.\\d/'", ",", "substr", "(", "$", "this", "->", "pdfdata", ",", "0", ",", "16", ")", ",", "$", "m", ")", ";", "if", "(", "isset", "(", "$", "m", "[", "0", "]", ")", ")", "$", "this", "->", "pdfVersion", "=", "$", "m", "[", "0", "]", ";", "return", "$", "this", "->", "pdfVersion", ";", "}" ]
Get PDF-Version And reset the PDF Version used in FPDI if needed @public
[ "Get", "PDF", "-", "Version" ]
8cede29130ba6b60d33481b4067a8cba24c21753
https://github.com/deltaaskii/lara-pdf-merger/blob/8cede29130ba6b60d33481b4067a8cba24c21753/src/LynX39/LaraPdfMerger/tcpdf/tcpdi_parser.php#L245-L250
37,641
deltaaskii/lara-pdf-merger
src/LynX39/LaraPdfMerger/PdfManage.php
PdfManage.merge
public function merge($outputmode = 'browser', $outputpath = 'newfile.pdf', $orientation = null, $meta = []) { if (!isset($this->_files) || !is_array($this->_files)) { throw new Exception("No PDFs to merge."); } $fpdi = new TCPDI; $fpdi->setPrintHeader(false); $fpdi->setPrintFooter(false); // setting the meta tags if (!empty($meta)) { $this->setMeta($meta); } // merger operations foreach ($this->_files as $file) { $filename = $file[0]; $filepages = $file[1]; $fileorientation = (!is_null($file[2])) ? $file[2] : $orientation; $count = $fpdi->setSourceFile($filename); //add the pages if ($filepages == 'all') { for ($i=1; $i<=$count; $i++) { $template = $fpdi->importPage($i); $size = $fpdi->getTemplateSize($template); if($orientation==null)$fileorientation=$size['w']< $size['h']?'P' : 'L'; $fpdi->AddPage($fileorientation, array($size['w'], $size['h'])); $fpdi->useTemplate($template); } } else { foreach ($filepages as $page) { if (!$template = $fpdi->importPage($page)) { throw new Exception("Could not load page '$page' in PDF '$filename'. Check that the page exists."); } $size = $fpdi->getTemplateSize($template); if($orientation==null)$fileorientation=$size['w']< $size['h']?'P' : 'L'; $fpdi->AddPage($fileorientation, array($size['w'], $size['h'])); $fpdi->useTemplate($template); } } } //output operations $mode = $this->_switchmode($outputmode); if ($mode == 'S') { return $fpdi->Output($outputpath, 'S'); } else { if ($fpdi->Output($outputpath, $mode) == '') { return true; } else { throw new Exception("Error outputting PDF to '$outputmode'."); return false; } } }
php
public function merge($outputmode = 'browser', $outputpath = 'newfile.pdf', $orientation = null, $meta = []) { if (!isset($this->_files) || !is_array($this->_files)) { throw new Exception("No PDFs to merge."); } $fpdi = new TCPDI; $fpdi->setPrintHeader(false); $fpdi->setPrintFooter(false); // setting the meta tags if (!empty($meta)) { $this->setMeta($meta); } // merger operations foreach ($this->_files as $file) { $filename = $file[0]; $filepages = $file[1]; $fileorientation = (!is_null($file[2])) ? $file[2] : $orientation; $count = $fpdi->setSourceFile($filename); //add the pages if ($filepages == 'all') { for ($i=1; $i<=$count; $i++) { $template = $fpdi->importPage($i); $size = $fpdi->getTemplateSize($template); if($orientation==null)$fileorientation=$size['w']< $size['h']?'P' : 'L'; $fpdi->AddPage($fileorientation, array($size['w'], $size['h'])); $fpdi->useTemplate($template); } } else { foreach ($filepages as $page) { if (!$template = $fpdi->importPage($page)) { throw new Exception("Could not load page '$page' in PDF '$filename'. Check that the page exists."); } $size = $fpdi->getTemplateSize($template); if($orientation==null)$fileorientation=$size['w']< $size['h']?'P' : 'L'; $fpdi->AddPage($fileorientation, array($size['w'], $size['h'])); $fpdi->useTemplate($template); } } } //output operations $mode = $this->_switchmode($outputmode); if ($mode == 'S') { return $fpdi->Output($outputpath, 'S'); } else { if ($fpdi->Output($outputpath, $mode) == '') { return true; } else { throw new Exception("Error outputting PDF to '$outputmode'."); return false; } } }
[ "public", "function", "merge", "(", "$", "outputmode", "=", "'browser'", ",", "$", "outputpath", "=", "'newfile.pdf'", ",", "$", "orientation", "=", "null", ",", "$", "meta", "=", "[", "]", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_files", ")", "||", "!", "is_array", "(", "$", "this", "->", "_files", ")", ")", "{", "throw", "new", "Exception", "(", "\"No PDFs to merge.\"", ")", ";", "}", "$", "fpdi", "=", "new", "TCPDI", ";", "$", "fpdi", "->", "setPrintHeader", "(", "false", ")", ";", "$", "fpdi", "->", "setPrintFooter", "(", "false", ")", ";", "// setting the meta tags", "if", "(", "!", "empty", "(", "$", "meta", ")", ")", "{", "$", "this", "->", "setMeta", "(", "$", "meta", ")", ";", "}", "// merger operations", "foreach", "(", "$", "this", "->", "_files", "as", "$", "file", ")", "{", "$", "filename", "=", "$", "file", "[", "0", "]", ";", "$", "filepages", "=", "$", "file", "[", "1", "]", ";", "$", "fileorientation", "=", "(", "!", "is_null", "(", "$", "file", "[", "2", "]", ")", ")", "?", "$", "file", "[", "2", "]", ":", "$", "orientation", ";", "$", "count", "=", "$", "fpdi", "->", "setSourceFile", "(", "$", "filename", ")", ";", "//add the pages", "if", "(", "$", "filepages", "==", "'all'", ")", "{", "for", "(", "$", "i", "=", "1", ";", "$", "i", "<=", "$", "count", ";", "$", "i", "++", ")", "{", "$", "template", "=", "$", "fpdi", "->", "importPage", "(", "$", "i", ")", ";", "$", "size", "=", "$", "fpdi", "->", "getTemplateSize", "(", "$", "template", ")", ";", "if", "(", "$", "orientation", "==", "null", ")", "$", "fileorientation", "=", "$", "size", "[", "'w'", "]", "<", "$", "size", "[", "'h'", "]", "?", "'P'", ":", "'L'", ";", "$", "fpdi", "->", "AddPage", "(", "$", "fileorientation", ",", "array", "(", "$", "size", "[", "'w'", "]", ",", "$", "size", "[", "'h'", "]", ")", ")", ";", "$", "fpdi", "->", "useTemplate", "(", "$", "template", ")", ";", "}", "}", "else", "{", "foreach", "(", "$", "filepages", "as", "$", "page", ")", "{", "if", "(", "!", "$", "template", "=", "$", "fpdi", "->", "importPage", "(", "$", "page", ")", ")", "{", "throw", "new", "Exception", "(", "\"Could not load page '$page' in PDF '$filename'. Check that the page exists.\"", ")", ";", "}", "$", "size", "=", "$", "fpdi", "->", "getTemplateSize", "(", "$", "template", ")", ";", "if", "(", "$", "orientation", "==", "null", ")", "$", "fileorientation", "=", "$", "size", "[", "'w'", "]", "<", "$", "size", "[", "'h'", "]", "?", "'P'", ":", "'L'", ";", "$", "fpdi", "->", "AddPage", "(", "$", "fileorientation", ",", "array", "(", "$", "size", "[", "'w'", "]", ",", "$", "size", "[", "'h'", "]", ")", ")", ";", "$", "fpdi", "->", "useTemplate", "(", "$", "template", ")", ";", "}", "}", "}", "//output operations", "$", "mode", "=", "$", "this", "->", "_switchmode", "(", "$", "outputmode", ")", ";", "if", "(", "$", "mode", "==", "'S'", ")", "{", "return", "$", "fpdi", "->", "Output", "(", "$", "outputpath", ",", "'S'", ")", ";", "}", "else", "{", "if", "(", "$", "fpdi", "->", "Output", "(", "$", "outputpath", ",", "$", "mode", ")", "==", "''", ")", "{", "return", "true", ";", "}", "else", "{", "throw", "new", "Exception", "(", "\"Error outputting PDF to '$outputmode'.\"", ")", ";", "return", "false", ";", "}", "}", "}" ]
Merges your provided PDFs and outputs to specified location. @param $outputmode @param $outputname @param $orientation @array $meta [title => $title, author => $author, subject => $subject, keywords => $keywords, creator => $creator] @return PDF
[ "Merges", "your", "provided", "PDFs", "and", "outputs", "to", "specified", "location", "." ]
8cede29130ba6b60d33481b4067a8cba24c21753
https://github.com/deltaaskii/lara-pdf-merger/blob/8cede29130ba6b60d33481b4067a8cba24c21753/src/LynX39/LaraPdfMerger/PdfManage.php#L45-L109
37,642
deltaaskii/lara-pdf-merger
src/LynX39/LaraPdfMerger/PdfManage.php
PdfManage.setMeta
protected function setMeta($fpdi, $meta) { foreach ($meta as $key => $arg) { $metodName = 'set' . ucfirst($key); if (method_exists($fpdi, $metodName)) { $fpdi->$metodName($arg); } } return $fpdi; }
php
protected function setMeta($fpdi, $meta) { foreach ($meta as $key => $arg) { $metodName = 'set' . ucfirst($key); if (method_exists($fpdi, $metodName)) { $fpdi->$metodName($arg); } } return $fpdi; }
[ "protected", "function", "setMeta", "(", "$", "fpdi", ",", "$", "meta", ")", "{", "foreach", "(", "$", "meta", "as", "$", "key", "=>", "$", "arg", ")", "{", "$", "metodName", "=", "'set'", ".", "ucfirst", "(", "$", "key", ")", ";", "if", "(", "method_exists", "(", "$", "fpdi", ",", "$", "metodName", ")", ")", "{", "$", "fpdi", "->", "$", "metodName", "(", "$", "arg", ")", ";", "}", "}", "return", "$", "fpdi", ";", "}" ]
Set your meta data in merged pdf @param $fpdi @array $meta [title => $title, author => $author, subject => $subject, keywords => $keywords, creator => $creator] @return void
[ "Set", "your", "meta", "data", "in", "merged", "pdf" ]
8cede29130ba6b60d33481b4067a8cba24c21753
https://github.com/deltaaskii/lara-pdf-merger/blob/8cede29130ba6b60d33481b4067a8cba24c21753/src/LynX39/LaraPdfMerger/PdfManage.php#L180-L189
37,643
ThaDafinser/ZfcDatagrid
src/ZfcDatagrid/Datagrid.php
Datagrid.setTranslator
public function setTranslator($translator = null) { if (!$translator instanceof Translator && !$translator instanceof \Zend\I18n\Translator\TranslatorInterface) { throw new \InvalidArgumentException('Translator must be an instanceof "Zend\I18n\Translator\Translator" or "Zend\I18n\Translator\TranslatorInterface"'); } $this->translator = $translator; }
php
public function setTranslator($translator = null) { if (!$translator instanceof Translator && !$translator instanceof \Zend\I18n\Translator\TranslatorInterface) { throw new \InvalidArgumentException('Translator must be an instanceof "Zend\I18n\Translator\Translator" or "Zend\I18n\Translator\TranslatorInterface"'); } $this->translator = $translator; }
[ "public", "function", "setTranslator", "(", "$", "translator", "=", "null", ")", "{", "if", "(", "!", "$", "translator", "instanceof", "Translator", "&&", "!", "$", "translator", "instanceof", "\\", "Zend", "\\", "I18n", "\\", "Translator", "\\", "TranslatorInterface", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Translator must be an instanceof \"Zend\\I18n\\Translator\\Translator\" or \"Zend\\I18n\\Translator\\TranslatorInterface\"'", ")", ";", "}", "$", "this", "->", "translator", "=", "$", "translator", ";", "}" ]
Set the translator. @param Translator $translator @throws \InvalidArgumentException
[ "Set", "the", "translator", "." ]
73b521e2df30510cb0ea9fcb9b7ed99147542597
https://github.com/ThaDafinser/ZfcDatagrid/blob/73b521e2df30510cb0ea9fcb9b7ed99147542597/src/ZfcDatagrid/Datagrid.php#L372-L379
37,644
denissimon/formula-parser
FormulaParser.php
FormulaParser.calculate1
private function calculate1(array $array) { for ($i=count($array)-1; $i>=0; $i--) { if (isset($array[$i]) && isset($array[$i-1]) && isset($array[$i+1]) && $array[$i] === '^') { $otp = 1; $this->checkInf($array[$i-1], $array[$i+1]); if (is_numeric($array[$i-1]) && is_numeric($array[$i+1])) { if ($array[$i-1] < 0) { $a = pow($array[$i-1]*-1, $array[$i+1]); $otp = 2; } else { $a = pow($array[$i-1], $array[$i+1]); } } else { $this->correct = 0; break; } unset($array[$i-1], $array[$i+1]); $array[$i] = ($otp == 1) ? $a : $a*-1; $array = array_values($array); $i = count($array)-1; } } return $array; }
php
private function calculate1(array $array) { for ($i=count($array)-1; $i>=0; $i--) { if (isset($array[$i]) && isset($array[$i-1]) && isset($array[$i+1]) && $array[$i] === '^') { $otp = 1; $this->checkInf($array[$i-1], $array[$i+1]); if (is_numeric($array[$i-1]) && is_numeric($array[$i+1])) { if ($array[$i-1] < 0) { $a = pow($array[$i-1]*-1, $array[$i+1]); $otp = 2; } else { $a = pow($array[$i-1], $array[$i+1]); } } else { $this->correct = 0; break; } unset($array[$i-1], $array[$i+1]); $array[$i] = ($otp == 1) ? $a : $a*-1; $array = array_values($array); $i = count($array)-1; } } return $array; }
[ "private", "function", "calculate1", "(", "array", "$", "array", ")", "{", "for", "(", "$", "i", "=", "count", "(", "$", "array", ")", "-", "1", ";", "$", "i", ">=", "0", ";", "$", "i", "--", ")", "{", "if", "(", "isset", "(", "$", "array", "[", "$", "i", "]", ")", "&&", "isset", "(", "$", "array", "[", "$", "i", "-", "1", "]", ")", "&&", "isset", "(", "$", "array", "[", "$", "i", "+", "1", "]", ")", "&&", "$", "array", "[", "$", "i", "]", "===", "'^'", ")", "{", "$", "otp", "=", "1", ";", "$", "this", "->", "checkInf", "(", "$", "array", "[", "$", "i", "-", "1", "]", ",", "$", "array", "[", "$", "i", "+", "1", "]", ")", ";", "if", "(", "is_numeric", "(", "$", "array", "[", "$", "i", "-", "1", "]", ")", "&&", "is_numeric", "(", "$", "array", "[", "$", "i", "+", "1", "]", ")", ")", "{", "if", "(", "$", "array", "[", "$", "i", "-", "1", "]", "<", "0", ")", "{", "$", "a", "=", "pow", "(", "$", "array", "[", "$", "i", "-", "1", "]", "*", "-", "1", ",", "$", "array", "[", "$", "i", "+", "1", "]", ")", ";", "$", "otp", "=", "2", ";", "}", "else", "{", "$", "a", "=", "pow", "(", "$", "array", "[", "$", "i", "-", "1", "]", ",", "$", "array", "[", "$", "i", "+", "1", "]", ")", ";", "}", "}", "else", "{", "$", "this", "->", "correct", "=", "0", ";", "break", ";", "}", "unset", "(", "$", "array", "[", "$", "i", "-", "1", "]", ",", "$", "array", "[", "$", "i", "+", "1", "]", ")", ";", "$", "array", "[", "$", "i", "]", "=", "(", "$", "otp", "==", "1", ")", "?", "$", "a", ":", "$", "a", "*", "-", "1", ";", "$", "array", "=", "array_values", "(", "$", "array", ")", ";", "$", "i", "=", "count", "(", "$", "array", ")", "-", "1", ";", "}", "}", "return", "$", "array", ";", "}" ]
Calculates an operation ^ @param array $array The subexpression of the formula @return array
[ "Calculates", "an", "operation", "^" ]
4caa5f566aea891bc6726031b4dcdcd75d67462b
https://github.com/denissimon/formula-parser/blob/4caa5f566aea891bc6726031b4dcdcd75d67462b/FormulaParser.php#L140-L165
37,645
denissimon/formula-parser
FormulaParser.php
FormulaParser.calculate3
private function calculate3(array $array) { for ($i=0; $i<count($array); $i++) { if (isset($array[$i]) && isset($array[$i-1]) && isset($array[$i+1]) && ($array[$i] === '+' || $array[$i] === '-')) { $this->checkInf($array[$i-1], $array[$i+1]); if (!is_numeric($array[$i-1]) || !is_numeric($array[$i+1])) { $this->correct = 0; break; } if ($array[$i] === '+') { $a = $array[$i-1] + $array[$i+1]; } elseif ($array[$i] === '-') { $a = $array[$i-1] - $array[$i+1]; } unset($array[$i-1], $array[$i+1]); $array[$i] = $a; $array = array_values($array); $i = 0; } } return $array; }
php
private function calculate3(array $array) { for ($i=0; $i<count($array); $i++) { if (isset($array[$i]) && isset($array[$i-1]) && isset($array[$i+1]) && ($array[$i] === '+' || $array[$i] === '-')) { $this->checkInf($array[$i-1], $array[$i+1]); if (!is_numeric($array[$i-1]) || !is_numeric($array[$i+1])) { $this->correct = 0; break; } if ($array[$i] === '+') { $a = $array[$i-1] + $array[$i+1]; } elseif ($array[$i] === '-') { $a = $array[$i-1] - $array[$i+1]; } unset($array[$i-1], $array[$i+1]); $array[$i] = $a; $array = array_values($array); $i = 0; } } return $array; }
[ "private", "function", "calculate3", "(", "array", "$", "array", ")", "{", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "array", ")", ";", "$", "i", "++", ")", "{", "if", "(", "isset", "(", "$", "array", "[", "$", "i", "]", ")", "&&", "isset", "(", "$", "array", "[", "$", "i", "-", "1", "]", ")", "&&", "isset", "(", "$", "array", "[", "$", "i", "+", "1", "]", ")", "&&", "(", "$", "array", "[", "$", "i", "]", "===", "'+'", "||", "$", "array", "[", "$", "i", "]", "===", "'-'", ")", ")", "{", "$", "this", "->", "checkInf", "(", "$", "array", "[", "$", "i", "-", "1", "]", ",", "$", "array", "[", "$", "i", "+", "1", "]", ")", ";", "if", "(", "!", "is_numeric", "(", "$", "array", "[", "$", "i", "-", "1", "]", ")", "||", "!", "is_numeric", "(", "$", "array", "[", "$", "i", "+", "1", "]", ")", ")", "{", "$", "this", "->", "correct", "=", "0", ";", "break", ";", "}", "if", "(", "$", "array", "[", "$", "i", "]", "===", "'+'", ")", "{", "$", "a", "=", "$", "array", "[", "$", "i", "-", "1", "]", "+", "$", "array", "[", "$", "i", "+", "1", "]", ";", "}", "elseif", "(", "$", "array", "[", "$", "i", "]", "===", "'-'", ")", "{", "$", "a", "=", "$", "array", "[", "$", "i", "-", "1", "]", "-", "$", "array", "[", "$", "i", "+", "1", "]", ";", "}", "unset", "(", "$", "array", "[", "$", "i", "-", "1", "]", ",", "$", "array", "[", "$", "i", "+", "1", "]", ")", ";", "$", "array", "[", "$", "i", "]", "=", "$", "a", ";", "$", "array", "=", "array_values", "(", "$", "array", ")", ";", "$", "i", "=", "0", ";", "}", "}", "return", "$", "array", ";", "}" ]
Calculates operations +, - @param array $array The subexpression of the formula @return array
[ "Calculates", "operations", "+", "-" ]
4caa5f566aea891bc6726031b4dcdcd75d67462b
https://github.com/denissimon/formula-parser/blob/4caa5f566aea891bc6726031b4dcdcd75d67462b/FormulaParser.php#L211-L233
37,646
denissimon/formula-parser
FormulaParser.php
FormulaParser.group
private function group(&$formula, $opt = 'init') { if ($opt == 'init') { // Numbers in E notation $formula = preg_replace_callback('/[\d\.]+( )?[eE]( )?[\+\-]?( )?[\d\.]+ /', [$this, 'match'], $formula); // Variables if (count($this->variables) > 0) { $valid_variables = implode("|", $this->valid_variables); $formula = preg_replace_callback('/[\+\-\*\/\^ ]('.$valid_variables.')[ \+\-\*\/\^]/', [$this, 'match1'], $formula); } } else { // Functions $valid_functions = implode("|", $this->valid_functions); $formula = preg_replace_callback('/('.$valid_functions.')( )?[\+\-]?( )?[\d\.eEINF]+ /', [$this, 'match2'], $formula); } }
php
private function group(&$formula, $opt = 'init') { if ($opt == 'init') { // Numbers in E notation $formula = preg_replace_callback('/[\d\.]+( )?[eE]( )?[\+\-]?( )?[\d\.]+ /', [$this, 'match'], $formula); // Variables if (count($this->variables) > 0) { $valid_variables = implode("|", $this->valid_variables); $formula = preg_replace_callback('/[\+\-\*\/\^ ]('.$valid_variables.')[ \+\-\*\/\^]/', [$this, 'match1'], $formula); } } else { // Functions $valid_functions = implode("|", $this->valid_functions); $formula = preg_replace_callback('/('.$valid_functions.')( )?[\+\-]?( )?[\d\.eEINF]+ /', [$this, 'match2'], $formula); } }
[ "private", "function", "group", "(", "&", "$", "formula", ",", "$", "opt", "=", "'init'", ")", "{", "if", "(", "$", "opt", "==", "'init'", ")", "{", "// Numbers in E notation", "$", "formula", "=", "preg_replace_callback", "(", "'/[\\d\\.]+( )?[eE]( )?[\\+\\-]?( )?[\\d\\.]+ /'", ",", "[", "$", "this", ",", "'match'", "]", ",", "$", "formula", ")", ";", "// Variables", "if", "(", "count", "(", "$", "this", "->", "variables", ")", ">", "0", ")", "{", "$", "valid_variables", "=", "implode", "(", "\"|\"", ",", "$", "this", "->", "valid_variables", ")", ";", "$", "formula", "=", "preg_replace_callback", "(", "'/[\\+\\-\\*\\/\\^ ]('", ".", "$", "valid_variables", ".", "')[ \\+\\-\\*\\/\\^]/'", ",", "[", "$", "this", ",", "'match1'", "]", ",", "$", "formula", ")", ";", "}", "}", "else", "{", "// Functions", "$", "valid_functions", "=", "implode", "(", "\"|\"", ",", "$", "this", "->", "valid_functions", ")", ";", "$", "formula", "=", "preg_replace_callback", "(", "'/('", ".", "$", "valid_functions", ".", "')( )?[\\+\\-]?( )?[\\d\\.eEINF]+ /'", ",", "[", "$", "this", ",", "'match2'", "]", ",", "$", "formula", ")", ";", "}", "}" ]
Groups the parts of the formula that must be evaluated first into parentheses @param string $formula @param string $opt
[ "Groups", "the", "parts", "of", "the", "formula", "that", "must", "be", "evaluated", "first", "into", "parentheses" ]
4caa5f566aea891bc6726031b4dcdcd75d67462b
https://github.com/denissimon/formula-parser/blob/4caa5f566aea891bc6726031b4dcdcd75d67462b/FormulaParser.php#L625-L642
37,647
AdrianSkierniewski/eloquent-tree
src/Gzero/EloquentTree/Model/Observer.php
Observer.saving
public function saving(Tree $model) { if (!$model->exists and !in_array('path', array_keys($model->attributesToArray()), TRUE)) { $model->{$model->getTreeColumn('path')} = ''; $model->{$model->getTreeColumn('parent')} = NULL; $model->{$model->getTreeColumn('level')} = 0; } }
php
public function saving(Tree $model) { if (!$model->exists and !in_array('path', array_keys($model->attributesToArray()), TRUE)) { $model->{$model->getTreeColumn('path')} = ''; $model->{$model->getTreeColumn('parent')} = NULL; $model->{$model->getTreeColumn('level')} = 0; } }
[ "public", "function", "saving", "(", "Tree", "$", "model", ")", "{", "if", "(", "!", "$", "model", "->", "exists", "and", "!", "in_array", "(", "'path'", ",", "array_keys", "(", "$", "model", "->", "attributesToArray", "(", ")", ")", ",", "TRUE", ")", ")", "{", "$", "model", "->", "{", "$", "model", "->", "getTreeColumn", "(", "'path'", ")", "}", "=", "''", ";", "$", "model", "->", "{", "$", "model", "->", "getTreeColumn", "(", "'parent'", ")", "}", "=", "NULL", ";", "$", "model", "->", "{", "$", "model", "->", "getTreeColumn", "(", "'level'", ")", "}", "=", "0", ";", "}", "}" ]
When saving node we must set path and level @param Tree $model
[ "When", "saving", "node", "we", "must", "set", "path", "and", "level" ]
de4065b9ef3977702d62227bf9a5afccb710fa82
https://github.com/AdrianSkierniewski/eloquent-tree/blob/de4065b9ef3977702d62227bf9a5afccb710fa82/src/Gzero/EloquentTree/Model/Observer.php#L18-L25
37,648
AdrianSkierniewski/eloquent-tree
src/Gzero/EloquentTree/Model/Observer.php
Observer.saved
public function saved(Tree $model) { if ($model->{$model->getTreeColumn('path')} === '') { // If we just save() new node $model->{$model->getTreeColumn('path')} = $model->getKey() . '/'; DB::connection($model->getConnectionName())->table($model->getTable()) ->where($model->getKeyName(), '=', $model->getKey()) ->update( array( $model->getTreeColumn('path') => $model->{$model->getTreeColumn('path')} ) ); } }
php
public function saved(Tree $model) { if ($model->{$model->getTreeColumn('path')} === '') { // If we just save() new node $model->{$model->getTreeColumn('path')} = $model->getKey() . '/'; DB::connection($model->getConnectionName())->table($model->getTable()) ->where($model->getKeyName(), '=', $model->getKey()) ->update( array( $model->getTreeColumn('path') => $model->{$model->getTreeColumn('path')} ) ); } }
[ "public", "function", "saved", "(", "Tree", "$", "model", ")", "{", "if", "(", "$", "model", "->", "{", "$", "model", "->", "getTreeColumn", "(", "'path'", ")", "}", "===", "''", ")", "{", "// If we just save() new node", "$", "model", "->", "{", "$", "model", "->", "getTreeColumn", "(", "'path'", ")", "}", "=", "$", "model", "->", "getKey", "(", ")", ".", "'/'", ";", "DB", "::", "connection", "(", "$", "model", "->", "getConnectionName", "(", ")", ")", "->", "table", "(", "$", "model", "->", "getTable", "(", ")", ")", "->", "where", "(", "$", "model", "->", "getKeyName", "(", ")", ",", "'='", ",", "$", "model", "->", "getKey", "(", ")", ")", "->", "update", "(", "array", "(", "$", "model", "->", "getTreeColumn", "(", "'path'", ")", "=>", "$", "model", "->", "{", "$", "model", "->", "getTreeColumn", "(", "'path'", ")", "}", ")", ")", ";", "}", "}" ]
After mode was saved we're building node path @param Tree $model
[ "After", "mode", "was", "saved", "we", "re", "building", "node", "path" ]
de4065b9ef3977702d62227bf9a5afccb710fa82
https://github.com/AdrianSkierniewski/eloquent-tree/blob/de4065b9ef3977702d62227bf9a5afccb710fa82/src/Gzero/EloquentTree/Model/Observer.php#L32-L44
37,649
AdrianSkierniewski/eloquent-tree
src/Gzero/EloquentTree/Model/Tree.php
Tree.setAsRoot
public function setAsRoot() { $this->handleNewNodes(); if (!$this->isRoot()) { // Only if it is not already root if ($this->fireModelEvent('updatingParent') === false) { return $this; } $oldDescendants = $this->getOldDescendants(); $this->{$this->getTreeColumn('path')} = $this->getKey() . '/'; $this->{$this->getTreeColumn('parent')} = null; $this->setRelation('parent', null); $this->{$this->getTreeColumn('level')} = 0; $this->save(); $this->fireModelEvent('updatedParent', false); $this->updateDescendants($this, $oldDescendants); } return $this; }
php
public function setAsRoot() { $this->handleNewNodes(); if (!$this->isRoot()) { // Only if it is not already root if ($this->fireModelEvent('updatingParent') === false) { return $this; } $oldDescendants = $this->getOldDescendants(); $this->{$this->getTreeColumn('path')} = $this->getKey() . '/'; $this->{$this->getTreeColumn('parent')} = null; $this->setRelation('parent', null); $this->{$this->getTreeColumn('level')} = 0; $this->save(); $this->fireModelEvent('updatedParent', false); $this->updateDescendants($this, $oldDescendants); } return $this; }
[ "public", "function", "setAsRoot", "(", ")", "{", "$", "this", "->", "handleNewNodes", "(", ")", ";", "if", "(", "!", "$", "this", "->", "isRoot", "(", ")", ")", "{", "// Only if it is not already root", "if", "(", "$", "this", "->", "fireModelEvent", "(", "'updatingParent'", ")", "===", "false", ")", "{", "return", "$", "this", ";", "}", "$", "oldDescendants", "=", "$", "this", "->", "getOldDescendants", "(", ")", ";", "$", "this", "->", "{", "$", "this", "->", "getTreeColumn", "(", "'path'", ")", "}", "=", "$", "this", "->", "getKey", "(", ")", ".", "'/'", ";", "$", "this", "->", "{", "$", "this", "->", "getTreeColumn", "(", "'parent'", ")", "}", "=", "null", ";", "$", "this", "->", "setRelation", "(", "'parent'", ",", "null", ")", ";", "$", "this", "->", "{", "$", "this", "->", "getTreeColumn", "(", "'level'", ")", "}", "=", "0", ";", "$", "this", "->", "save", "(", ")", ";", "$", "this", "->", "fireModelEvent", "(", "'updatedParent'", ",", "false", ")", ";", "$", "this", "->", "updateDescendants", "(", "$", "this", ",", "$", "oldDescendants", ")", ";", "}", "return", "$", "this", ";", "}" ]
Set node as root node @return $this
[ "Set", "node", "as", "root", "node" ]
de4065b9ef3977702d62227bf9a5afccb710fa82
https://github.com/AdrianSkierniewski/eloquent-tree/blob/de4065b9ef3977702d62227bf9a5afccb710fa82/src/Gzero/EloquentTree/Model/Tree.php#L46-L63
37,650
AdrianSkierniewski/eloquent-tree
src/Gzero/EloquentTree/Model/Tree.php
Tree.validateSetChildOf
public function validateSetChildOf(Tree $parent) { if ($parent->getKey() == $this->getKey()) { throw new SelfConnectionException(); } if ($parent->{$this->getTreeColumn('path')} != $this->removeLastNodeFromPath()) { // Only if new parent return true; } return false; }
php
public function validateSetChildOf(Tree $parent) { if ($parent->getKey() == $this->getKey()) { throw new SelfConnectionException(); } if ($parent->{$this->getTreeColumn('path')} != $this->removeLastNodeFromPath()) { // Only if new parent return true; } return false; }
[ "public", "function", "validateSetChildOf", "(", "Tree", "$", "parent", ")", "{", "if", "(", "$", "parent", "->", "getKey", "(", ")", "==", "$", "this", "->", "getKey", "(", ")", ")", "{", "throw", "new", "SelfConnectionException", "(", ")", ";", "}", "if", "(", "$", "parent", "->", "{", "$", "this", "->", "getTreeColumn", "(", "'path'", ")", "}", "!=", "$", "this", "->", "removeLastNodeFromPath", "(", ")", ")", "{", "// Only if new parent", "return", "true", ";", "}", "return", "false", ";", "}" ]
Validate if parent change and prevent self connection @param Tree $parent New parent node @return bool @throws Exception\SelfConnectionException
[ "Validate", "if", "parent", "change", "and", "prevent", "self", "connection" ]
de4065b9ef3977702d62227bf9a5afccb710fa82
https://github.com/AdrianSkierniewski/eloquent-tree/blob/de4065b9ef3977702d62227bf9a5afccb710fa82/src/Gzero/EloquentTree/Model/Tree.php#L98-L107
37,651
AdrianSkierniewski/eloquent-tree
src/Gzero/EloquentTree/Model/Tree.php
Tree.findDescendants
public function findDescendants() { return static::where($this->getTreeColumn('path'), 'LIKE', $this->{$this->getTreeColumn('path')} . '%') ->orderBy($this->getTreeColumn('level'), 'ASC'); }
php
public function findDescendants() { return static::where($this->getTreeColumn('path'), 'LIKE', $this->{$this->getTreeColumn('path')} . '%') ->orderBy($this->getTreeColumn('level'), 'ASC'); }
[ "public", "function", "findDescendants", "(", ")", "{", "return", "static", "::", "where", "(", "$", "this", "->", "getTreeColumn", "(", "'path'", ")", ",", "'LIKE'", ",", "$", "this", "->", "{", "$", "this", "->", "getTreeColumn", "(", "'path'", ")", "}", ".", "'%'", ")", "->", "orderBy", "(", "$", "this", "->", "getTreeColumn", "(", "'level'", ")", ",", "'ASC'", ")", ";", "}" ]
Find all descendants for specific node with this node as root @return \Illuminate\Database\Eloquent\Builder
[ "Find", "all", "descendants", "for", "specific", "node", "with", "this", "node", "as", "root" ]
de4065b9ef3977702d62227bf9a5afccb710fa82
https://github.com/AdrianSkierniewski/eloquent-tree/blob/de4065b9ef3977702d62227bf9a5afccb710fa82/src/Gzero/EloquentTree/Model/Tree.php#L197-L201
37,652
AdrianSkierniewski/eloquent-tree
src/Gzero/EloquentTree/Model/Tree.php
Tree.findRoot
public function findRoot() { if ($this->isRoot()) { return $this; } else { $extractedPath = $this->extractPath(); $root_id = array_shift($extractedPath); return static::where($this->getKeyName(), '=', $root_id)->first(); } }
php
public function findRoot() { if ($this->isRoot()) { return $this; } else { $extractedPath = $this->extractPath(); $root_id = array_shift($extractedPath); return static::where($this->getKeyName(), '=', $root_id)->first(); } }
[ "public", "function", "findRoot", "(", ")", "{", "if", "(", "$", "this", "->", "isRoot", "(", ")", ")", "{", "return", "$", "this", ";", "}", "else", "{", "$", "extractedPath", "=", "$", "this", "->", "extractPath", "(", ")", ";", "$", "root_id", "=", "array_shift", "(", "$", "extractedPath", ")", ";", "return", "static", "::", "where", "(", "$", "this", "->", "getKeyName", "(", ")", ",", "'='", ",", "$", "root_id", ")", "->", "first", "(", ")", ";", "}", "}" ]
Find root for this node @return $this
[ "Find", "root", "for", "this", "node" ]
de4065b9ef3977702d62227bf9a5afccb710fa82
https://github.com/AdrianSkierniewski/eloquent-tree/blob/de4065b9ef3977702d62227bf9a5afccb710fa82/src/Gzero/EloquentTree/Model/Tree.php#L219-L228
37,653
AdrianSkierniewski/eloquent-tree
src/Gzero/EloquentTree/Model/Tree.php
Tree.buildTree
public function buildTree(Collection $nodes, $strict = true) { $refs = []; // Reference table to store records in the construction of the tree $count = 0; $roots = new Collection(); foreach ($nodes as &$node) { /* @var Tree $node */ $node->initChildrenRelation(); // We need to init relation to avoid LAZY LOADING in future $refs[$node->getKey()] = &$node; // Adding to ref table (we identify after the id) if ($count === 0) { $roots->add($node); $count++; } else { if ($this->siblingOfRoot($node, $roots)) { // We use this condition as a factor in building subtrees $roots->add($node); } else { // This is not a root, so add them to the parent $index = $node->{$this->getTreeColumn('parent')}; if (!empty($refs[$index])) { // We should already have parent for our node added to refs array $refs[$index]->addChildToCollection($node); } else { if ($strict) { // We don't want to ignore orphan nodes throw new MissingParentException(); } } } } } if (!empty($roots)) { if (count($roots) > 1) { return $roots; } else { return $roots->first(); } } else { return false; } }
php
public function buildTree(Collection $nodes, $strict = true) { $refs = []; // Reference table to store records in the construction of the tree $count = 0; $roots = new Collection(); foreach ($nodes as &$node) { /* @var Tree $node */ $node->initChildrenRelation(); // We need to init relation to avoid LAZY LOADING in future $refs[$node->getKey()] = &$node; // Adding to ref table (we identify after the id) if ($count === 0) { $roots->add($node); $count++; } else { if ($this->siblingOfRoot($node, $roots)) { // We use this condition as a factor in building subtrees $roots->add($node); } else { // This is not a root, so add them to the parent $index = $node->{$this->getTreeColumn('parent')}; if (!empty($refs[$index])) { // We should already have parent for our node added to refs array $refs[$index]->addChildToCollection($node); } else { if ($strict) { // We don't want to ignore orphan nodes throw new MissingParentException(); } } } } } if (!empty($roots)) { if (count($roots) > 1) { return $roots; } else { return $roots->first(); } } else { return false; } }
[ "public", "function", "buildTree", "(", "Collection", "$", "nodes", ",", "$", "strict", "=", "true", ")", "{", "$", "refs", "=", "[", "]", ";", "// Reference table to store records in the construction of the tree", "$", "count", "=", "0", ";", "$", "roots", "=", "new", "Collection", "(", ")", ";", "foreach", "(", "$", "nodes", "as", "&", "$", "node", ")", "{", "/* @var Tree $node */", "$", "node", "->", "initChildrenRelation", "(", ")", ";", "// We need to init relation to avoid LAZY LOADING in future", "$", "refs", "[", "$", "node", "->", "getKey", "(", ")", "]", "=", "&", "$", "node", ";", "// Adding to ref table (we identify after the id)", "if", "(", "$", "count", "===", "0", ")", "{", "$", "roots", "->", "add", "(", "$", "node", ")", ";", "$", "count", "++", ";", "}", "else", "{", "if", "(", "$", "this", "->", "siblingOfRoot", "(", "$", "node", ",", "$", "roots", ")", ")", "{", "// We use this condition as a factor in building subtrees", "$", "roots", "->", "add", "(", "$", "node", ")", ";", "}", "else", "{", "// This is not a root, so add them to the parent", "$", "index", "=", "$", "node", "->", "{", "$", "this", "->", "getTreeColumn", "(", "'parent'", ")", "}", ";", "if", "(", "!", "empty", "(", "$", "refs", "[", "$", "index", "]", ")", ")", "{", "// We should already have parent for our node added to refs array", "$", "refs", "[", "$", "index", "]", "->", "addChildToCollection", "(", "$", "node", ")", ";", "}", "else", "{", "if", "(", "$", "strict", ")", "{", "// We don't want to ignore orphan nodes", "throw", "new", "MissingParentException", "(", ")", ";", "}", "}", "}", "}", "}", "if", "(", "!", "empty", "(", "$", "roots", ")", ")", "{", "if", "(", "count", "(", "$", "roots", ")", ">", "1", ")", "{", "return", "$", "roots", ";", "}", "else", "{", "return", "$", "roots", "->", "first", "(", ")", ";", "}", "}", "else", "{", "return", "false", ";", "}", "}" ]
Rebuilds trees from passed nodes @param Collection $nodes Nodes from which we are build tree @param bool $strict If we want to make sure that there are no orphan nodes @return static Root node @throws MissingParentException
[ "Rebuilds", "trees", "from", "passed", "nodes" ]
de4065b9ef3977702d62227bf9a5afccb710fa82
https://github.com/AdrianSkierniewski/eloquent-tree/blob/de4065b9ef3977702d62227bf9a5afccb710fa82/src/Gzero/EloquentTree/Model/Tree.php#L239-L276
37,654
AdrianSkierniewski/eloquent-tree
src/Gzero/EloquentTree/Model/Tree.php
Tree.getLeaves
public static function getLeaves() { $parents = static::select('parent_id')->whereNotNull('parent_id')->distinct()->get()->pluck('parent_id')->all(); return static::wherenotin('id',$parents); }
php
public static function getLeaves() { $parents = static::select('parent_id')->whereNotNull('parent_id')->distinct()->get()->pluck('parent_id')->all(); return static::wherenotin('id',$parents); }
[ "public", "static", "function", "getLeaves", "(", ")", "{", "$", "parents", "=", "static", "::", "select", "(", "'parent_id'", ")", "->", "whereNotNull", "(", "'parent_id'", ")", "->", "distinct", "(", ")", "->", "get", "(", ")", "->", "pluck", "(", "'parent_id'", ")", "->", "all", "(", ")", ";", "return", "static", "::", "wherenotin", "(", "'id'", ",", "$", "parents", ")", ";", "}" ]
Gets all leaf nodes @return \Illuminate\Database\Eloquent\Builder
[ "Gets", "all", "leaf", "nodes" ]
de4065b9ef3977702d62227bf9a5afccb710fa82
https://github.com/AdrianSkierniewski/eloquent-tree/blob/de4065b9ef3977702d62227bf9a5afccb710fa82/src/Gzero/EloquentTree/Model/Tree.php#L352-L356
37,655
AdrianSkierniewski/eloquent-tree
src/Gzero/EloquentTree/Model/Tree.php
Tree.renderRecursiveTree
protected function renderRecursiveTree($node, $tag, Callable $render) { $out = ''; $out .= '<' . $tag . ' class="tree tree-level-' . ($node->{$node->getTreeColumn('level')} + 1) . '">'; foreach ($node->children as $child) { if (!empty($child->children)) { $level = $render($child); $nextLevel = $this->renderRecursiveTree($child, $tag, $render); $out .= preg_replace('/{sub-tree}/', $nextLevel, $level); } else { $out .= preg_replace('/{sub-tree}/', '', $render($child)); } } return $out . '</' . $tag . '>'; }
php
protected function renderRecursiveTree($node, $tag, Callable $render) { $out = ''; $out .= '<' . $tag . ' class="tree tree-level-' . ($node->{$node->getTreeColumn('level')} + 1) . '">'; foreach ($node->children as $child) { if (!empty($child->children)) { $level = $render($child); $nextLevel = $this->renderRecursiveTree($child, $tag, $render); $out .= preg_replace('/{sub-tree}/', $nextLevel, $level); } else { $out .= preg_replace('/{sub-tree}/', '', $render($child)); } } return $out . '</' . $tag . '>'; }
[ "protected", "function", "renderRecursiveTree", "(", "$", "node", ",", "$", "tag", ",", "Callable", "$", "render", ")", "{", "$", "out", "=", "''", ";", "$", "out", ".=", "'<'", ".", "$", "tag", ".", "' class=\"tree tree-level-'", ".", "(", "$", "node", "->", "{", "$", "node", "->", "getTreeColumn", "(", "'level'", ")", "}", "+", "1", ")", ".", "'\">'", ";", "foreach", "(", "$", "node", "->", "children", "as", "$", "child", ")", "{", "if", "(", "!", "empty", "(", "$", "child", "->", "children", ")", ")", "{", "$", "level", "=", "$", "render", "(", "$", "child", ")", ";", "$", "nextLevel", "=", "$", "this", "->", "renderRecursiveTree", "(", "$", "child", ",", "$", "tag", ",", "$", "render", ")", ";", "$", "out", ".=", "preg_replace", "(", "'/{sub-tree}/'", ",", "$", "nextLevel", ",", "$", "level", ")", ";", "}", "else", "{", "$", "out", ".=", "preg_replace", "(", "'/{sub-tree}/'", ",", "''", ",", "$", "render", "(", "$", "child", ")", ")", ";", "}", "}", "return", "$", "out", ".", "'</'", ".", "$", "tag", ".", "'>'", ";", "}" ]
Recursive render descendants @param $node @param $tag @param callable $render @return string
[ "Recursive", "render", "descendants" ]
de4065b9ef3977702d62227bf9a5afccb710fa82
https://github.com/AdrianSkierniewski/eloquent-tree/blob/de4065b9ef3977702d62227bf9a5afccb710fa82/src/Gzero/EloquentTree/Model/Tree.php#L518-L532
37,656
AdrianSkierniewski/eloquent-tree
src/Gzero/EloquentTree/Model/Tree.php
Tree.updateDescendants
protected function updateDescendants(Tree $node, $oldDescendants) { $refs = []; $refs[$node->getKey()] = &$node; // Updated node foreach ($oldDescendants as &$child) { $refs[$child->getKey()] = $child; $parent_id = $child->{$this->getTreeColumn('parent')}; if (!empty($refs[$parent_id])) { if ($refs[$parent_id]->path != $refs[$child->getKey()]->removeLastNodeFromPath()) { $refs[$child->getKey()]->level = $refs[$parent_id]->level + 1; // New level $refs[$child->getKey()]->path = $refs[$parent_id]->path . $child->getKey() . '/'; // New path DB::table($this->getTable()) ->where($child->getKeyName(), '=', $child->getKey()) ->update( [ $this->getTreeColumn('level') => $refs[$child->getKey()]->level, $this->getTreeColumn('path') => $refs[$child->getKey()]->path ] ); } } } $this->fireModelEvent('updatedDescendants', false); }
php
protected function updateDescendants(Tree $node, $oldDescendants) { $refs = []; $refs[$node->getKey()] = &$node; // Updated node foreach ($oldDescendants as &$child) { $refs[$child->getKey()] = $child; $parent_id = $child->{$this->getTreeColumn('parent')}; if (!empty($refs[$parent_id])) { if ($refs[$parent_id]->path != $refs[$child->getKey()]->removeLastNodeFromPath()) { $refs[$child->getKey()]->level = $refs[$parent_id]->level + 1; // New level $refs[$child->getKey()]->path = $refs[$parent_id]->path . $child->getKey() . '/'; // New path DB::table($this->getTable()) ->where($child->getKeyName(), '=', $child->getKey()) ->update( [ $this->getTreeColumn('level') => $refs[$child->getKey()]->level, $this->getTreeColumn('path') => $refs[$child->getKey()]->path ] ); } } } $this->fireModelEvent('updatedDescendants', false); }
[ "protected", "function", "updateDescendants", "(", "Tree", "$", "node", ",", "$", "oldDescendants", ")", "{", "$", "refs", "=", "[", "]", ";", "$", "refs", "[", "$", "node", "->", "getKey", "(", ")", "]", "=", "&", "$", "node", ";", "// Updated node", "foreach", "(", "$", "oldDescendants", "as", "&", "$", "child", ")", "{", "$", "refs", "[", "$", "child", "->", "getKey", "(", ")", "]", "=", "$", "child", ";", "$", "parent_id", "=", "$", "child", "->", "{", "$", "this", "->", "getTreeColumn", "(", "'parent'", ")", "}", ";", "if", "(", "!", "empty", "(", "$", "refs", "[", "$", "parent_id", "]", ")", ")", "{", "if", "(", "$", "refs", "[", "$", "parent_id", "]", "->", "path", "!=", "$", "refs", "[", "$", "child", "->", "getKey", "(", ")", "]", "->", "removeLastNodeFromPath", "(", ")", ")", "{", "$", "refs", "[", "$", "child", "->", "getKey", "(", ")", "]", "->", "level", "=", "$", "refs", "[", "$", "parent_id", "]", "->", "level", "+", "1", ";", "// New level", "$", "refs", "[", "$", "child", "->", "getKey", "(", ")", "]", "->", "path", "=", "$", "refs", "[", "$", "parent_id", "]", "->", "path", ".", "$", "child", "->", "getKey", "(", ")", ".", "'/'", ";", "// New path", "DB", "::", "table", "(", "$", "this", "->", "getTable", "(", ")", ")", "->", "where", "(", "$", "child", "->", "getKeyName", "(", ")", ",", "'='", ",", "$", "child", "->", "getKey", "(", ")", ")", "->", "update", "(", "[", "$", "this", "->", "getTreeColumn", "(", "'level'", ")", "=>", "$", "refs", "[", "$", "child", "->", "getKey", "(", ")", "]", "->", "level", ",", "$", "this", "->", "getTreeColumn", "(", "'path'", ")", "=>", "$", "refs", "[", "$", "child", "->", "getKey", "(", ")", "]", "->", "path", "]", ")", ";", "}", "}", "}", "$", "this", "->", "fireModelEvent", "(", "'updatedDescendants'", ",", "false", ")", ";", "}" ]
Updating descendants nodes @param Tree $node Updated node @param Collection $oldDescendants Old descendants collection (just before modify parent)
[ "Updating", "descendants", "nodes" ]
de4065b9ef3977702d62227bf9a5afccb710fa82
https://github.com/AdrianSkierniewski/eloquent-tree/blob/de4065b9ef3977702d62227bf9a5afccb710fa82/src/Gzero/EloquentTree/Model/Tree.php#L541-L564
37,657
AdrianSkierniewski/eloquent-tree
src/Gzero/EloquentTree/Model/Tree.php
Tree.siblingOfRoot
private function siblingOfRoot(Tree $node, Collection $roots) { return (bool) $roots->filter( function ($item) use ($node) { return $node->isSibling($item); } )->first(); }
php
private function siblingOfRoot(Tree $node, Collection $roots) { return (bool) $roots->filter( function ($item) use ($node) { return $node->isSibling($item); } )->first(); }
[ "private", "function", "siblingOfRoot", "(", "Tree", "$", "node", ",", "Collection", "$", "roots", ")", "{", "return", "(", "bool", ")", "$", "roots", "->", "filter", "(", "function", "(", "$", "item", ")", "use", "(", "$", "node", ")", "{", "return", "$", "node", "->", "isSibling", "(", "$", "item", ")", ";", "}", ")", "->", "first", "(", ")", ";", "}" ]
Check if node is sibling for roots in collection @param Tree $node Tree node @param Collection $roots Collection of roots @return bool
[ "Check", "if", "node", "is", "sibling", "for", "roots", "in", "collection" ]
de4065b9ef3977702d62227bf9a5afccb710fa82
https://github.com/AdrianSkierniewski/eloquent-tree/blob/de4065b9ef3977702d62227bf9a5afccb710fa82/src/Gzero/EloquentTree/Model/Tree.php#L574-L581
37,658
Lecturize/Laravel-Addresses
src/Traits/HasContacts.php
HasContacts.addContact
public function addContact(array $attributes) { $attributes = $this->loadContactAttributes($attributes); return $this->contacts()->updateOrCreate($attributes); }
php
public function addContact(array $attributes) { $attributes = $this->loadContactAttributes($attributes); return $this->contacts()->updateOrCreate($attributes); }
[ "public", "function", "addContact", "(", "array", "$", "attributes", ")", "{", "$", "attributes", "=", "$", "this", "->", "loadContactAttributes", "(", "$", "attributes", ")", ";", "return", "$", "this", "->", "contacts", "(", ")", "->", "updateOrCreate", "(", "$", "attributes", ")", ";", "}" ]
Add a contact to this model. @param array $attributes @return mixed @throws \Exception
[ "Add", "a", "contact", "to", "this", "model", "." ]
2e528b76c9be285e72ce53f2d82e55923cd5fce8
https://github.com/Lecturize/Laravel-Addresses/blob/2e528b76c9be285e72ce53f2d82e55923cd5fce8/src/Traits/HasContacts.php#L40-L45
37,659
Lecturize/Laravel-Addresses
src/Traits/HasContacts.php
HasContacts.deleteContact
public function deleteContact(Contact $contact) { if ($this !== $contact->contactable()->first()) return false; return $contact->delete(); }
php
public function deleteContact(Contact $contact) { if ($this !== $contact->contactable()->first()) return false; return $contact->delete(); }
[ "public", "function", "deleteContact", "(", "Contact", "$", "contact", ")", "{", "if", "(", "$", "this", "!==", "$", "contact", "->", "contactable", "(", ")", "->", "first", "(", ")", ")", "return", "false", ";", "return", "$", "contact", "->", "delete", "(", ")", ";", "}" ]
Deletes given contact. @param Contact $contact @return bool @throws \Exception
[ "Deletes", "given", "contact", "." ]
2e528b76c9be285e72ce53f2d82e55923cd5fce8
https://github.com/Lecturize/Laravel-Addresses/blob/2e528b76c9be285e72ce53f2d82e55923cd5fce8/src/Traits/HasContacts.php#L71-L77
37,660
Lecturize/Laravel-Addresses
src/Models/Address.php
Address.geocode
public function geocode() { // build query string $query = []; $query[] = $this->street ?: ''; $query[] = $this->street_extra ?: ''; $query[] = $this->city ?: ''; $query[] = $this->state ?: ''; $query[] = $this->post_code ?: ''; $query[] = $this->getCountry() ?: ''; // build query string $query = trim(implode(',', array_filter($query))); $query = str_replace(' ', '+', $query); if (! $query) return $this; // build url $url = 'https://maps.google.com/maps/api/geocode/json?address='. $query .'&sensor=false'; // try to get geo codes if ($geocode = file_get_contents($url)) { $output = json_decode($geocode); if (count($output->results) && isset($output->results[0])) { if ($geo = $output->results[0]->geometry) { $this->lat = $geo->location->lat; $this->lng = $geo->location->lng; } } } return $this; }
php
public function geocode() { // build query string $query = []; $query[] = $this->street ?: ''; $query[] = $this->street_extra ?: ''; $query[] = $this->city ?: ''; $query[] = $this->state ?: ''; $query[] = $this->post_code ?: ''; $query[] = $this->getCountry() ?: ''; // build query string $query = trim(implode(',', array_filter($query))); $query = str_replace(' ', '+', $query); if (! $query) return $this; // build url $url = 'https://maps.google.com/maps/api/geocode/json?address='. $query .'&sensor=false'; // try to get geo codes if ($geocode = file_get_contents($url)) { $output = json_decode($geocode); if (count($output->results) && isset($output->results[0])) { if ($geo = $output->results[0]->geometry) { $this->lat = $geo->location->lat; $this->lng = $geo->location->lng; } } } return $this; }
[ "public", "function", "geocode", "(", ")", "{", "// build query string", "$", "query", "=", "[", "]", ";", "$", "query", "[", "]", "=", "$", "this", "->", "street", "?", ":", "''", ";", "$", "query", "[", "]", "=", "$", "this", "->", "street_extra", "?", ":", "''", ";", "$", "query", "[", "]", "=", "$", "this", "->", "city", "?", ":", "''", ";", "$", "query", "[", "]", "=", "$", "this", "->", "state", "?", ":", "''", ";", "$", "query", "[", "]", "=", "$", "this", "->", "post_code", "?", ":", "''", ";", "$", "query", "[", "]", "=", "$", "this", "->", "getCountry", "(", ")", "?", ":", "''", ";", "// build query string", "$", "query", "=", "trim", "(", "implode", "(", "','", ",", "array_filter", "(", "$", "query", ")", ")", ")", ";", "$", "query", "=", "str_replace", "(", "' '", ",", "'+'", ",", "$", "query", ")", ";", "if", "(", "!", "$", "query", ")", "return", "$", "this", ";", "// build url", "$", "url", "=", "'https://maps.google.com/maps/api/geocode/json?address='", ".", "$", "query", ".", "'&sensor=false'", ";", "// try to get geo codes", "if", "(", "$", "geocode", "=", "file_get_contents", "(", "$", "url", ")", ")", "{", "$", "output", "=", "json_decode", "(", "$", "geocode", ")", ";", "if", "(", "count", "(", "$", "output", "->", "results", ")", "&&", "isset", "(", "$", "output", "->", "results", "[", "0", "]", ")", ")", "{", "if", "(", "$", "geo", "=", "$", "output", "->", "results", "[", "0", "]", "->", "geometry", ")", "{", "$", "this", "->", "lat", "=", "$", "geo", "->", "location", "->", "lat", ";", "$", "this", "->", "lng", "=", "$", "geo", "->", "location", "->", "lng", ";", "}", "}", "}", "return", "$", "this", ";", "}" ]
Try to fetch the coordinates from Google and store them. @return $this
[ "Try", "to", "fetch", "the", "coordinates", "from", "Google", "and", "store", "them", "." ]
2e528b76c9be285e72ce53f2d82e55923cd5fce8
https://github.com/Lecturize/Laravel-Addresses/blob/2e528b76c9be285e72ce53f2d82e55923cd5fce8/src/Models/Address.php#L103-L137
37,661
Lecturize/Laravel-Addresses
src/Models/Address.php
Address.getArray
public function getArray() { $address = $two = []; $two[] = $this->post_code ?: ''; $two[] = $this->city ?: ''; $two[] = $this->state ? '('. $this->state .')' : ''; $address[] = $this->street ?: ''; $address[] = $this->street_extra ?: ''; $address[] = implode(' ', array_filter($two)); $address[] = $this->country_name ?: ''; if (count($address = array_filter($address)) > 0) return $address; return null; }
php
public function getArray() { $address = $two = []; $two[] = $this->post_code ?: ''; $two[] = $this->city ?: ''; $two[] = $this->state ? '('. $this->state .')' : ''; $address[] = $this->street ?: ''; $address[] = $this->street_extra ?: ''; $address[] = implode(' ', array_filter($two)); $address[] = $this->country_name ?: ''; if (count($address = array_filter($address)) > 0) return $address; return null; }
[ "public", "function", "getArray", "(", ")", "{", "$", "address", "=", "$", "two", "=", "[", "]", ";", "$", "two", "[", "]", "=", "$", "this", "->", "post_code", "?", ":", "''", ";", "$", "two", "[", "]", "=", "$", "this", "->", "city", "?", ":", "''", ";", "$", "two", "[", "]", "=", "$", "this", "->", "state", "?", "'('", ".", "$", "this", "->", "state", ".", "')'", ":", "''", ";", "$", "address", "[", "]", "=", "$", "this", "->", "street", "?", ":", "''", ";", "$", "address", "[", "]", "=", "$", "this", "->", "street_extra", "?", ":", "''", ";", "$", "address", "[", "]", "=", "implode", "(", "' '", ",", "array_filter", "(", "$", "two", ")", ")", ";", "$", "address", "[", "]", "=", "$", "this", "->", "country_name", "?", ":", "''", ";", "if", "(", "count", "(", "$", "address", "=", "array_filter", "(", "$", "address", ")", ")", ">", "0", ")", "return", "$", "address", ";", "return", "null", ";", "}" ]
Get the address as array. @return array
[ "Get", "the", "address", "as", "array", "." ]
2e528b76c9be285e72ce53f2d82e55923cd5fce8
https://github.com/Lecturize/Laravel-Addresses/blob/2e528b76c9be285e72ce53f2d82e55923cd5fce8/src/Models/Address.php#L144-L161
37,662
Lecturize/Laravel-Addresses
src/Models/Address.php
Address.getLine
public function getLine($glue = ', ') { if ($address = $this->getArray()) return implode($glue, array_filter($address)); return null; }
php
public function getLine($glue = ', ') { if ($address = $this->getArray()) return implode($glue, array_filter($address)); return null; }
[ "public", "function", "getLine", "(", "$", "glue", "=", "', '", ")", "{", "if", "(", "$", "address", "=", "$", "this", "->", "getArray", "(", ")", ")", "return", "implode", "(", "$", "glue", ",", "array_filter", "(", "$", "address", ")", ")", ";", "return", "null", ";", "}" ]
Get the address as a simple line. @param string $glue @return string
[ "Get", "the", "address", "as", "a", "simple", "line", "." ]
2e528b76c9be285e72ce53f2d82e55923cd5fce8
https://github.com/Lecturize/Laravel-Addresses/blob/2e528b76c9be285e72ce53f2d82e55923cd5fce8/src/Models/Address.php#L182-L188
37,663
Lecturize/Laravel-Addresses
src/Models/Address.php
Address.getCountryCodeAttribute
public function getCountryCodeAttribute($digits = 2) { if (! $this->country) return ''; if ($digits === 3) return $this->country->iso_3166_3; return $this->country->iso_3166_2; }
php
public function getCountryCodeAttribute($digits = 2) { if (! $this->country) return ''; if ($digits === 3) return $this->country->iso_3166_3; return $this->country->iso_3166_2; }
[ "public", "function", "getCountryCodeAttribute", "(", "$", "digits", "=", "2", ")", "{", "if", "(", "!", "$", "this", "->", "country", ")", "return", "''", ";", "if", "(", "$", "digits", "===", "3", ")", "return", "$", "this", "->", "country", "->", "iso_3166_3", ";", "return", "$", "this", "->", "country", "->", "iso_3166_2", ";", "}" ]
Get the country code. @param int $digits @return string
[ "Get", "the", "country", "code", "." ]
2e528b76c9be285e72ce53f2d82e55923cd5fce8
https://github.com/Lecturize/Laravel-Addresses/blob/2e528b76c9be285e72ce53f2d82e55923cd5fce8/src/Models/Address.php#L223-L232
37,664
Lecturize/Laravel-Addresses
src/Traits/HasAddresses.php
HasAddresses.addAddress
public function addAddress(array $attributes) { $attributes = $this->loadAddressAttributes($attributes); return $this->addresses()->updateOrCreate($attributes); }
php
public function addAddress(array $attributes) { $attributes = $this->loadAddressAttributes($attributes); return $this->addresses()->updateOrCreate($attributes); }
[ "public", "function", "addAddress", "(", "array", "$", "attributes", ")", "{", "$", "attributes", "=", "$", "this", "->", "loadAddressAttributes", "(", "$", "attributes", ")", ";", "return", "$", "this", "->", "addresses", "(", ")", "->", "updateOrCreate", "(", "$", "attributes", ")", ";", "}" ]
Add an address to this model. @param array $attributes @return mixed @throws \Exception
[ "Add", "an", "address", "to", "this", "model", "." ]
2e528b76c9be285e72ce53f2d82e55923cd5fce8
https://github.com/Lecturize/Laravel-Addresses/blob/2e528b76c9be285e72ce53f2d82e55923cd5fce8/src/Traits/HasAddresses.php#L41-L46
37,665
Lecturize/Laravel-Addresses
src/Traits/HasAddresses.php
HasAddresses.deleteAddress
public function deleteAddress(Address $address) { if ($this !== $address->addressable()->first()) return false; return $address->delete(); }
php
public function deleteAddress(Address $address) { if ($this !== $address->addressable()->first()) return false; return $address->delete(); }
[ "public", "function", "deleteAddress", "(", "Address", "$", "address", ")", "{", "if", "(", "$", "this", "!==", "$", "address", "->", "addressable", "(", ")", "->", "first", "(", ")", ")", "return", "false", ";", "return", "$", "address", "->", "delete", "(", ")", ";", "}" ]
Deletes given address. @param Address $address @return bool @throws \Exception
[ "Deletes", "given", "address", "." ]
2e528b76c9be285e72ce53f2d82e55923cd5fce8
https://github.com/Lecturize/Laravel-Addresses/blob/2e528b76c9be285e72ce53f2d82e55923cd5fce8/src/Traits/HasAddresses.php#L72-L78
37,666
Lecturize/Laravel-Addresses
src/Models/Contact.php
Contact.getFullNameAttribute
public function getFullNameAttribute() { $names = []; $names[] = $this->first_name ?: ''; $names[] = $this->middle_name ?: ''; $names[] = $this->last_name ?: ''; return trim(implode(' ', array_filter($names))); }
php
public function getFullNameAttribute() { $names = []; $names[] = $this->first_name ?: ''; $names[] = $this->middle_name ?: ''; $names[] = $this->last_name ?: ''; return trim(implode(' ', array_filter($names))); }
[ "public", "function", "getFullNameAttribute", "(", ")", "{", "$", "names", "=", "[", "]", ";", "$", "names", "[", "]", "=", "$", "this", "->", "first_name", "?", ":", "''", ";", "$", "names", "[", "]", "=", "$", "this", "->", "middle_name", "?", ":", "''", ";", "$", "names", "[", "]", "=", "$", "this", "->", "last_name", "?", ":", "''", ";", "return", "trim", "(", "implode", "(", "' '", ",", "array_filter", "(", "$", "names", ")", ")", ")", ";", "}" ]
Get the contacts full name. @return string
[ "Get", "the", "contacts", "full", "name", "." ]
2e528b76c9be285e72ce53f2d82e55923cd5fce8
https://github.com/Lecturize/Laravel-Addresses/blob/2e528b76c9be285e72ce53f2d82e55923cd5fce8/src/Models/Contact.php#L75-L83
37,667
Lecturize/Laravel-Addresses
src/Models/Contact.php
Contact.getFullNameRevAttribute
public function getFullNameRevAttribute() { $first = []; $first[] = $this->first_name ?: ''; $first[] = $this->middle_name ?: ''; $names = []; $names[] = $this->last_name ?: ''; $names[] = implode(' ', array_filter($first)); return trim(implode(', ', array_filter($names))); }
php
public function getFullNameRevAttribute() { $first = []; $first[] = $this->first_name ?: ''; $first[] = $this->middle_name ?: ''; $names = []; $names[] = $this->last_name ?: ''; $names[] = implode(' ', array_filter($first)); return trim(implode(', ', array_filter($names))); }
[ "public", "function", "getFullNameRevAttribute", "(", ")", "{", "$", "first", "=", "[", "]", ";", "$", "first", "[", "]", "=", "$", "this", "->", "first_name", "?", ":", "''", ";", "$", "first", "[", "]", "=", "$", "this", "->", "middle_name", "?", ":", "''", ";", "$", "names", "=", "[", "]", ";", "$", "names", "[", "]", "=", "$", "this", "->", "last_name", "?", ":", "''", ";", "$", "names", "[", "]", "=", "implode", "(", "' '", ",", "array_filter", "(", "$", "first", ")", ")", ";", "return", "trim", "(", "implode", "(", "', '", ",", "array_filter", "(", "$", "names", ")", ")", ")", ";", "}" ]
Get the contacts full name, reversed. @return string
[ "Get", "the", "contacts", "full", "name", "reversed", "." ]
2e528b76c9be285e72ce53f2d82e55923cd5fce8
https://github.com/Lecturize/Laravel-Addresses/blob/2e528b76c9be285e72ce53f2d82e55923cd5fce8/src/Models/Contact.php#L90-L101
37,668
Lecturize/Laravel-Addresses
src/Traits/HasCountry.php
HasCountry.scopeByCountry
public function scopeByCountry( $query, $id ) { return $query->whereHas('country', function($q) use($id) { $q->where('id', $id); }); }
php
public function scopeByCountry( $query, $id ) { return $query->whereHas('country', function($q) use($id) { $q->where('id', $id); }); }
[ "public", "function", "scopeByCountry", "(", "$", "query", ",", "$", "id", ")", "{", "return", "$", "query", "->", "whereHas", "(", "'country'", ",", "function", "(", "$", "q", ")", "use", "(", "$", "id", ")", "{", "$", "q", "->", "where", "(", "'id'", ",", "$", "id", ")", ";", "}", ")", ";", "}" ]
Scope by country. @param object $query @param integer $id @return mixed
[ "Scope", "by", "country", "." ]
2e528b76c9be285e72ce53f2d82e55923cd5fce8
https://github.com/Lecturize/Laravel-Addresses/blob/2e528b76c9be285e72ce53f2d82e55923cd5fce8/src/Traits/HasCountry.php#L28-L33
37,669
experius/Magento-2-Module-Experius-WysiwygDownloads
Image/Adapter/Gd2.php
Gd2.open
public function open($filename) { $pathInfo = pathinfo($filename); if (!key_exists('extension', $pathInfo) || !in_array($pathInfo['extension'], $this->settings->getExtraFiletypes())) { parent::open($filename); } }
php
public function open($filename) { $pathInfo = pathinfo($filename); if (!key_exists('extension', $pathInfo) || !in_array($pathInfo['extension'], $this->settings->getExtraFiletypes())) { parent::open($filename); } }
[ "public", "function", "open", "(", "$", "filename", ")", "{", "$", "pathInfo", "=", "pathinfo", "(", "$", "filename", ")", ";", "if", "(", "!", "key_exists", "(", "'extension'", ",", "$", "pathInfo", ")", "||", "!", "in_array", "(", "$", "pathInfo", "[", "'extension'", "]", ",", "$", "this", "->", "settings", "->", "getExtraFiletypes", "(", ")", ")", ")", "{", "parent", "::", "open", "(", "$", "filename", ")", ";", "}", "}" ]
Open image for processing @param string $filename @return void @throws \OverflowException
[ "Open", "image", "for", "processing" ]
b857c11e1e0e03126f30dd9b9256548045937535
https://github.com/experius/Magento-2-Module-Experius-WysiwygDownloads/blob/b857c11e1e0e03126f30dd9b9256548045937535/Image/Adapter/Gd2.php#L32-L38
37,670
experius/Magento-2-Module-Experius-WysiwygDownloads
Image/Adapter/Gd2.php
Gd2.save
public function save($destination = null, $newName = null) { $fileName = $this->_prepareDestination($destination, $newName); $pathInfo = pathinfo($fileName); if (!key_exists('extension', $pathInfo) || !in_array($pathInfo['extension'], $this->settings->getExtraFiletypes())) { parent::save($destination, $newName); } }
php
public function save($destination = null, $newName = null) { $fileName = $this->_prepareDestination($destination, $newName); $pathInfo = pathinfo($fileName); if (!key_exists('extension', $pathInfo) || !in_array($pathInfo['extension'], $this->settings->getExtraFiletypes())) { parent::save($destination, $newName); } }
[ "public", "function", "save", "(", "$", "destination", "=", "null", ",", "$", "newName", "=", "null", ")", "{", "$", "fileName", "=", "$", "this", "->", "_prepareDestination", "(", "$", "destination", ",", "$", "newName", ")", ";", "$", "pathInfo", "=", "pathinfo", "(", "$", "fileName", ")", ";", "if", "(", "!", "key_exists", "(", "'extension'", ",", "$", "pathInfo", ")", "||", "!", "in_array", "(", "$", "pathInfo", "[", "'extension'", "]", ",", "$", "this", "->", "settings", "->", "getExtraFiletypes", "(", ")", ")", ")", "{", "parent", "::", "save", "(", "$", "destination", ",", "$", "newName", ")", ";", "}", "}" ]
Save image to specific path. If some folders of path does not exist they will be created @param null|string $destination @param null|string $newName @return void @throws \Exception If destination path is not writable
[ "Save", "image", "to", "specific", "path", ".", "If", "some", "folders", "of", "path", "does", "not", "exist", "they", "will", "be", "created" ]
b857c11e1e0e03126f30dd9b9256548045937535
https://github.com/experius/Magento-2-Module-Experius-WysiwygDownloads/blob/b857c11e1e0e03126f30dd9b9256548045937535/Image/Adapter/Gd2.php#L49-L56
37,671
experius/Magento-2-Module-Experius-WysiwygDownloads
Helper/Settings.php
Settings.getStoreId
public function getStoreId() { if (!$this->_storeId){ $this->_storeId = $this->_storeManager->getStore()->getId(); } return $this->_storeId; }
php
public function getStoreId() { if (!$this->_storeId){ $this->_storeId = $this->_storeManager->getStore()->getId(); } return $this->_storeId; }
[ "public", "function", "getStoreId", "(", ")", "{", "if", "(", "!", "$", "this", "->", "_storeId", ")", "{", "$", "this", "->", "_storeId", "=", "$", "this", "->", "_storeManager", "->", "getStore", "(", ")", "->", "getId", "(", ")", ";", "}", "return", "$", "this", "->", "_storeId", ";", "}" ]
Set a specified store ID value @param int $store @return $this
[ "Set", "a", "specified", "store", "ID", "value" ]
b857c11e1e0e03126f30dd9b9256548045937535
https://github.com/experius/Magento-2-Module-Experius-WysiwygDownloads/blob/b857c11e1e0e03126f30dd9b9256548045937535/Helper/Settings.php#L51-L57
37,672
ziplr/php-qr-code
src/qrencode.php
QRrawcode.getCode
public function getCode() { $ret; if($this->count < $this->dataLength) { $row = $this->count % $this->blocks; $col = $this->count / $this->blocks; if($col >= $this->rsblocks[0]->dataLength) { $row += $this->b1; } $ret = $this->rsblocks[$row]->data[$col]; } else if($this->count < $this->dataLength + $this->eccLength) { $row = ($this->count - $this->dataLength) % $this->blocks; $col = ($this->count - $this->dataLength) / $this->blocks; $ret = $this->rsblocks[$row]->ecc[$col]; } else { return 0; } $this->count++; return $ret; }
php
public function getCode() { $ret; if($this->count < $this->dataLength) { $row = $this->count % $this->blocks; $col = $this->count / $this->blocks; if($col >= $this->rsblocks[0]->dataLength) { $row += $this->b1; } $ret = $this->rsblocks[$row]->data[$col]; } else if($this->count < $this->dataLength + $this->eccLength) { $row = ($this->count - $this->dataLength) % $this->blocks; $col = ($this->count - $this->dataLength) / $this->blocks; $ret = $this->rsblocks[$row]->ecc[$col]; } else { return 0; } $this->count++; return $ret; }
[ "public", "function", "getCode", "(", ")", "{", "$", "ret", ";", "if", "(", "$", "this", "->", "count", "<", "$", "this", "->", "dataLength", ")", "{", "$", "row", "=", "$", "this", "->", "count", "%", "$", "this", "->", "blocks", ";", "$", "col", "=", "$", "this", "->", "count", "/", "$", "this", "->", "blocks", ";", "if", "(", "$", "col", ">=", "$", "this", "->", "rsblocks", "[", "0", "]", "->", "dataLength", ")", "{", "$", "row", "+=", "$", "this", "->", "b1", ";", "}", "$", "ret", "=", "$", "this", "->", "rsblocks", "[", "$", "row", "]", "->", "data", "[", "$", "col", "]", ";", "}", "else", "if", "(", "$", "this", "->", "count", "<", "$", "this", "->", "dataLength", "+", "$", "this", "->", "eccLength", ")", "{", "$", "row", "=", "(", "$", "this", "->", "count", "-", "$", "this", "->", "dataLength", ")", "%", "$", "this", "->", "blocks", ";", "$", "col", "=", "(", "$", "this", "->", "count", "-", "$", "this", "->", "dataLength", ")", "/", "$", "this", "->", "blocks", ";", "$", "ret", "=", "$", "this", "->", "rsblocks", "[", "$", "row", "]", "->", "ecc", "[", "$", "col", "]", ";", "}", "else", "{", "return", "0", ";", "}", "$", "this", "->", "count", "++", ";", "return", "$", "ret", ";", "}" ]
Gets ECC code @return Integer ECC byte for current object position
[ "Gets", "ECC", "code" ]
9988012930e9c2c20c5f8de4883ab010b674090b
https://github.com/ziplr/php-qr-code/blob/9988012930e9c2c20c5f8de4883ab010b674090b/src/qrencode.php#L162-L183
37,673
ziplr/php-qr-code
src/qrencode.php
QRcode.raw
public static function raw($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) { $enc = QRencode::factory($level, $size, $margin); return $enc->encodeRAW($text, $outfile); }
php
public static function raw($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4) { $enc = QRencode::factory($level, $size, $margin); return $enc->encodeRAW($text, $outfile); }
[ "public", "static", "function", "raw", "(", "$", "text", ",", "$", "outfile", "=", "false", ",", "$", "level", "=", "QR_ECLEVEL_L", ",", "$", "size", "=", "3", ",", "$", "margin", "=", "4", ")", "{", "$", "enc", "=", "QRencode", "::", "factory", "(", "$", "level", ",", "$", "size", ",", "$", "margin", ")", ";", "return", "$", "enc", "->", "encodeRAW", "(", "$", "text", ",", "$", "outfile", ")", ";", "}" ]
Creates Raw Array containing QR-Code. Simple helper function to create QR-Code array with one static call. @param String $text text string to encode @param Boolean $outfile (optional) not used, shuold be __false__ @param Integer $level (optional) error correction level __QR_ECLEVEL_L__, __QR_ECLEVEL_M__, __QR_ECLEVEL_Q__ or __QR_ECLEVEL_H__ @param Integer $size (optional) pixel size, multiplier for each 'virtual' pixel @param Integer $margin (optional) code margin (silent zone) in 'virtual' pixels @return Array containing Raw QR code
[ "Creates", "Raw", "Array", "containing", "QR", "-", "Code", ".", "Simple", "helper", "function", "to", "create", "QR", "-", "Code", "array", "with", "one", "static", "call", "." ]
9988012930e9c2c20c5f8de4883ab010b674090b
https://github.com/ziplr/php-qr-code/blob/9988012930e9c2c20c5f8de4883ab010b674090b/src/qrencode.php#L422-L426
37,674
ziplr/php-qr-code
src/qrencode.php
QRcode.canvas
public static function canvas($text, $elemId = false, $level = QR_ECLEVEL_L, $width = false, $size = false, $margin = 4, $autoInclude = false) { $html = ''; $extra = ''; if ($autoInclude) { if (!self::$jscanvasincluded) { self::$jscanvasincluded = true; echo '<script type="text/javascript" src="qrcanvas.js"></script>'; } } $enc = QRencode::factory($level, 1, 0); $tab_src = $enc->encode($text, false); $area = new QRcanvasOutput($tab_src); $area->detectGroups(); $area->detectAreas(); if ($elemId === false) { $elemId = 'qrcode-'.md5(mt_rand(1000,1000000).'.'.mt_rand(1000,1000000).'.'.mt_rand(1000,1000000).'.'.mt_rand(1000,1000000)); if ($width == false) { if (($size !== false) && ($size > 0)) { $width = ($area->getWidth()+(2*$margin)) * $size; } else { $width = ($area->getWidth()+(2*$margin)) * 4; } } $html .= '<canvas id="'.$elemId.'" width="'.$width.'" height="'.$width.'">Your browser does not support CANVAS tag! Please upgrade to modern version of FireFox, Opera, Chrome or Safari/Webkit based browser</canvas>'; } if ($width !== false) { $extra .= ', '.$width.', '.$width; } if ($margin !== false) { $extra .= ', '.$margin.', '.$margin; } $html .= '<script>if(eval("typeof "+\'QRdrawCode\'+"==\'function\'")){QRdrawCode(QRdecompactOps(\''.$area->getCanvasOps().'\')'."\n".', \''.$elemId.'\', '.$area->getWidth().' '.$extra.');}else{alert(\'Please include qrcanvas.js!\');}</script>'; return $html; }
php
public static function canvas($text, $elemId = false, $level = QR_ECLEVEL_L, $width = false, $size = false, $margin = 4, $autoInclude = false) { $html = ''; $extra = ''; if ($autoInclude) { if (!self::$jscanvasincluded) { self::$jscanvasincluded = true; echo '<script type="text/javascript" src="qrcanvas.js"></script>'; } } $enc = QRencode::factory($level, 1, 0); $tab_src = $enc->encode($text, false); $area = new QRcanvasOutput($tab_src); $area->detectGroups(); $area->detectAreas(); if ($elemId === false) { $elemId = 'qrcode-'.md5(mt_rand(1000,1000000).'.'.mt_rand(1000,1000000).'.'.mt_rand(1000,1000000).'.'.mt_rand(1000,1000000)); if ($width == false) { if (($size !== false) && ($size > 0)) { $width = ($area->getWidth()+(2*$margin)) * $size; } else { $width = ($area->getWidth()+(2*$margin)) * 4; } } $html .= '<canvas id="'.$elemId.'" width="'.$width.'" height="'.$width.'">Your browser does not support CANVAS tag! Please upgrade to modern version of FireFox, Opera, Chrome or Safari/Webkit based browser</canvas>'; } if ($width !== false) { $extra .= ', '.$width.', '.$width; } if ($margin !== false) { $extra .= ', '.$margin.', '.$margin; } $html .= '<script>if(eval("typeof "+\'QRdrawCode\'+"==\'function\'")){QRdrawCode(QRdecompactOps(\''.$area->getCanvasOps().'\')'."\n".', \''.$elemId.'\', '.$area->getWidth().' '.$extra.');}else{alert(\'Please include qrcanvas.js!\');}</script>'; return $html; }
[ "public", "static", "function", "canvas", "(", "$", "text", ",", "$", "elemId", "=", "false", ",", "$", "level", "=", "QR_ECLEVEL_L", ",", "$", "width", "=", "false", ",", "$", "size", "=", "false", ",", "$", "margin", "=", "4", ",", "$", "autoInclude", "=", "false", ")", "{", "$", "html", "=", "''", ";", "$", "extra", "=", "''", ";", "if", "(", "$", "autoInclude", ")", "{", "if", "(", "!", "self", "::", "$", "jscanvasincluded", ")", "{", "self", "::", "$", "jscanvasincluded", "=", "true", ";", "echo", "'<script type=\"text/javascript\" src=\"qrcanvas.js\"></script>'", ";", "}", "}", "$", "enc", "=", "QRencode", "::", "factory", "(", "$", "level", ",", "1", ",", "0", ")", ";", "$", "tab_src", "=", "$", "enc", "->", "encode", "(", "$", "text", ",", "false", ")", ";", "$", "area", "=", "new", "QRcanvasOutput", "(", "$", "tab_src", ")", ";", "$", "area", "->", "detectGroups", "(", ")", ";", "$", "area", "->", "detectAreas", "(", ")", ";", "if", "(", "$", "elemId", "===", "false", ")", "{", "$", "elemId", "=", "'qrcode-'", ".", "md5", "(", "mt_rand", "(", "1000", ",", "1000000", ")", ".", "'.'", ".", "mt_rand", "(", "1000", ",", "1000000", ")", ".", "'.'", ".", "mt_rand", "(", "1000", ",", "1000000", ")", ".", "'.'", ".", "mt_rand", "(", "1000", ",", "1000000", ")", ")", ";", "if", "(", "$", "width", "==", "false", ")", "{", "if", "(", "(", "$", "size", "!==", "false", ")", "&&", "(", "$", "size", ">", "0", ")", ")", "{", "$", "width", "=", "(", "$", "area", "->", "getWidth", "(", ")", "+", "(", "2", "*", "$", "margin", ")", ")", "*", "$", "size", ";", "}", "else", "{", "$", "width", "=", "(", "$", "area", "->", "getWidth", "(", ")", "+", "(", "2", "*", "$", "margin", ")", ")", "*", "4", ";", "}", "}", "$", "html", ".=", "'<canvas id=\"'", ".", "$", "elemId", ".", "'\" width=\"'", ".", "$", "width", ".", "'\" height=\"'", ".", "$", "width", ".", "'\">Your browser does not support CANVAS tag! Please upgrade to modern version of FireFox, Opera, Chrome or Safari/Webkit based browser</canvas>'", ";", "}", "if", "(", "$", "width", "!==", "false", ")", "{", "$", "extra", ".=", "', '", ".", "$", "width", ".", "', '", ".", "$", "width", ";", "}", "if", "(", "$", "margin", "!==", "false", ")", "{", "$", "extra", ".=", "', '", ".", "$", "margin", ".", "', '", ".", "$", "margin", ";", "}", "$", "html", ".=", "'<script>if(eval(\"typeof \"+\\'QRdrawCode\\'+\"==\\'function\\'\")){QRdrawCode(QRdecompactOps(\\''", ".", "$", "area", "->", "getCanvasOps", "(", ")", ".", "'\\')'", ".", "\"\\n\"", ".", "', \\''", ".", "$", "elemId", ".", "'\\', '", ".", "$", "area", "->", "getWidth", "(", ")", ".", "' '", ".", "$", "extra", ".", "');}else{alert(\\'Please include qrcanvas.js!\\');}</script>'", ";", "return", "$", "html", ";", "}" ]
Creates Html+JS code to draw QR-Code with HTML5 Canvas. Simple helper function to create QR-Code array with one static call. @param String $text text string to encode @param String $elemId (optional) target Canvas tag id attribute, if __false__ Canvas tag with auto id will be created @param Integer $level (optional) error correction level __QR_ECLEVEL_L__, __QR_ECLEVEL_M__, __QR_ECLEVEL_Q__ or __QR_ECLEVEL_H__ @param Integer $width (optional) CANVAS element width (sam as height) @param Integer $size (optional) pixel size, multiplier for each 'virtual' pixel @param Integer $margin (optional) code margin (silent zone) in 'virtual' pixels @param Boolean $autoInclude (optional) if __true__, required qrcanvas.js lib will be included (only once) @return String containing JavaScript creating the code, Canvas element (when $elemId is __false__) and script tag with required lib (when $autoInclude is __true__ and not yet included)
[ "Creates", "Html", "+", "JS", "code", "to", "draw", "QR", "-", "Code", "with", "HTML5", "Canvas", ".", "Simple", "helper", "function", "to", "create", "QR", "-", "Code", "array", "with", "one", "static", "call", "." ]
9988012930e9c2c20c5f8de4883ab010b674090b
https://github.com/ziplr/php-qr-code/blob/9988012930e9c2c20c5f8de4883ab010b674090b/src/qrencode.php#L442-L485
37,675
ziplr/php-qr-code
src/qrencode.php
QRcode.svg
public static function svg($text, $elemId = false, $outFile = false, $level = QR_ECLEVEL_L, $width = false, $size = false, $margin = 4, $compress = false) { $enc = QRencode::factory($level, 1, 0); $tab_src = $enc->encode($text, false); $area = new QRsvgOutput($tab_src); $area->detectGroups(); $area->detectAreas(); if ($elemId === false) { $elemId = 'qrcode-'.md5(mt_rand(1000,1000000).'.'.mt_rand(1000,1000000).'.'.mt_rand(1000,1000000).'.'.mt_rand(1000,1000000)); if ($width == false) { if (($size !== false) && ($size > 0)) { $width = ($area->getWidth()+(2*$margin)) * $size; } else { $width = ($area->getWidth()+(2*$margin)) * 4; } } } $svg = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="full" viewBox="'.(-$margin).' '.(-$margin).' '.($area->getWidth()+($margin*2)).' '.($area->getWidth()+($margin*2)).'" width="'.$width.'" height="'.$width.'" id="'.$elemId.'">'."\n"; $svg .= $area->getRawSvg().'</svg>'; if ($outFile !== false) { $xmlPreamble = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>'."\n"; $svgContent = $xmlPreamble.$svg; if ($compress === true) { file_put_contents($outFile, gzencode($svgContent)); } else { file_put_contents($outFile, $svgContent); } } return $svg; }
php
public static function svg($text, $elemId = false, $outFile = false, $level = QR_ECLEVEL_L, $width = false, $size = false, $margin = 4, $compress = false) { $enc = QRencode::factory($level, 1, 0); $tab_src = $enc->encode($text, false); $area = new QRsvgOutput($tab_src); $area->detectGroups(); $area->detectAreas(); if ($elemId === false) { $elemId = 'qrcode-'.md5(mt_rand(1000,1000000).'.'.mt_rand(1000,1000000).'.'.mt_rand(1000,1000000).'.'.mt_rand(1000,1000000)); if ($width == false) { if (($size !== false) && ($size > 0)) { $width = ($area->getWidth()+(2*$margin)) * $size; } else { $width = ($area->getWidth()+(2*$margin)) * 4; } } } $svg = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="full" viewBox="'.(-$margin).' '.(-$margin).' '.($area->getWidth()+($margin*2)).' '.($area->getWidth()+($margin*2)).'" width="'.$width.'" height="'.$width.'" id="'.$elemId.'">'."\n"; $svg .= $area->getRawSvg().'</svg>'; if ($outFile !== false) { $xmlPreamble = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>'."\n"; $svgContent = $xmlPreamble.$svg; if ($compress === true) { file_put_contents($outFile, gzencode($svgContent)); } else { file_put_contents($outFile, $svgContent); } } return $svg; }
[ "public", "static", "function", "svg", "(", "$", "text", ",", "$", "elemId", "=", "false", ",", "$", "outFile", "=", "false", ",", "$", "level", "=", "QR_ECLEVEL_L", ",", "$", "width", "=", "false", ",", "$", "size", "=", "false", ",", "$", "margin", "=", "4", ",", "$", "compress", "=", "false", ")", "{", "$", "enc", "=", "QRencode", "::", "factory", "(", "$", "level", ",", "1", ",", "0", ")", ";", "$", "tab_src", "=", "$", "enc", "->", "encode", "(", "$", "text", ",", "false", ")", ";", "$", "area", "=", "new", "QRsvgOutput", "(", "$", "tab_src", ")", ";", "$", "area", "->", "detectGroups", "(", ")", ";", "$", "area", "->", "detectAreas", "(", ")", ";", "if", "(", "$", "elemId", "===", "false", ")", "{", "$", "elemId", "=", "'qrcode-'", ".", "md5", "(", "mt_rand", "(", "1000", ",", "1000000", ")", ".", "'.'", ".", "mt_rand", "(", "1000", ",", "1000000", ")", ".", "'.'", ".", "mt_rand", "(", "1000", ",", "1000000", ")", ".", "'.'", ".", "mt_rand", "(", "1000", ",", "1000000", ")", ")", ";", "if", "(", "$", "width", "==", "false", ")", "{", "if", "(", "(", "$", "size", "!==", "false", ")", "&&", "(", "$", "size", ">", "0", ")", ")", "{", "$", "width", "=", "(", "$", "area", "->", "getWidth", "(", ")", "+", "(", "2", "*", "$", "margin", ")", ")", "*", "$", "size", ";", "}", "else", "{", "$", "width", "=", "(", "$", "area", "->", "getWidth", "(", ")", "+", "(", "2", "*", "$", "margin", ")", ")", "*", "4", ";", "}", "}", "}", "$", "svg", "=", "'<svg xmlns=\"http://www.w3.org/2000/svg\"\n xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n version=\"1.1\"\n baseProfile=\"full\"\n viewBox=\"'", ".", "(", "-", "$", "margin", ")", ".", "' '", ".", "(", "-", "$", "margin", ")", ".", "' '", ".", "(", "$", "area", "->", "getWidth", "(", ")", "+", "(", "$", "margin", "*", "2", ")", ")", ".", "' '", ".", "(", "$", "area", "->", "getWidth", "(", ")", "+", "(", "$", "margin", "*", "2", ")", ")", ".", "'\" \n width=\"'", ".", "$", "width", ".", "'\"\n height=\"'", ".", "$", "width", ".", "'\"\n id=\"'", ".", "$", "elemId", ".", "'\">'", ".", "\"\\n\"", ";", "$", "svg", ".=", "$", "area", "->", "getRawSvg", "(", ")", ".", "'</svg>'", ";", "if", "(", "$", "outFile", "!==", "false", ")", "{", "$", "xmlPreamble", "=", "'<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>'", ".", "\"\\n\"", ";", "$", "svgContent", "=", "$", "xmlPreamble", ".", "$", "svg", ";", "if", "(", "$", "compress", "===", "true", ")", "{", "file_put_contents", "(", "$", "outFile", ",", "gzencode", "(", "$", "svgContent", ")", ")", ";", "}", "else", "{", "file_put_contents", "(", "$", "outFile", ",", "$", "svgContent", ")", ";", "}", "}", "return", "$", "svg", ";", "}" ]
Creates SVG with QR-Code. Simple helper function to create QR-Code SVG with one static call. @param String $text text string to encode @param Boolean $elemId (optional) target SVG tag id attribute, if __false__ SVG tag with auto id will be created @param String $outfile (optional) output file name, when __false__ file is not saved @param Integer $level (optional) error correction level __QR_ECLEVEL_L__, __QR_ECLEVEL_M__, __QR_ECLEVEL_Q__ or __QR_ECLEVEL_H__ @param Integer $width (optional) SVG element width (sam as height) @param Integer $size (optional) pixel size, multiplier for each 'virtual' pixel @param Integer $margin (optional) code margin (silent zone) in 'virtual' pixels @param Boolean $compress (optional) if __true__, compressed SVGZ (instead plaintext SVG) is saved to file @return String containing SVG tag
[ "Creates", "SVG", "with", "QR", "-", "Code", ".", "Simple", "helper", "function", "to", "create", "QR", "-", "Code", "SVG", "with", "one", "static", "call", "." ]
9988012930e9c2c20c5f8de4883ab010b674090b
https://github.com/ziplr/php-qr-code/blob/9988012930e9c2c20c5f8de4883ab010b674090b/src/qrencode.php#L502-L545
37,676
ziplr/php-qr-code
src/qrspec.php
QRspec.getDataLength
public static function getDataLength($version, $level) { return self::$capacity[$version][QRCAP_WORDS] - self::$capacity[$version][QRCAP_EC][$level]; }
php
public static function getDataLength($version, $level) { return self::$capacity[$version][QRCAP_WORDS] - self::$capacity[$version][QRCAP_EC][$level]; }
[ "public", "static", "function", "getDataLength", "(", "$", "version", ",", "$", "level", ")", "{", "return", "self", "::", "$", "capacity", "[", "$", "version", "]", "[", "QRCAP_WORDS", "]", "-", "self", "::", "$", "capacity", "[", "$", "version", "]", "[", "QRCAP_EC", "]", "[", "$", "level", "]", ";", "}" ]
Calculates data length for specified code configuration. @param Integer $version Code version @param Integer $level ECC level @returns Code data capacity
[ "Calculates", "data", "length", "for", "specified", "code", "configuration", "." ]
9988012930e9c2c20c5f8de4883ab010b674090b
https://github.com/ziplr/php-qr-code/blob/9988012930e9c2c20c5f8de4883ab010b674090b/src/qrspec.php#L115-L118
37,677
ziplr/php-qr-code
src/qrspec.php
QRspec.putAlignmentMarker
public static function putAlignmentMarker(array &$frame, $ox, $oy) { $finder = array( "\xa1\xa1\xa1\xa1\xa1", "\xa1\xa0\xa0\xa0\xa1", "\xa1\xa0\xa1\xa0\xa1", "\xa1\xa0\xa0\xa0\xa1", "\xa1\xa1\xa1\xa1\xa1" ); $yStart = $oy-2; $xStart = $ox-2; for($y=0; $y<5; $y++) { self::set($frame, $xStart, $yStart+$y, $finder[$y]); } }
php
public static function putAlignmentMarker(array &$frame, $ox, $oy) { $finder = array( "\xa1\xa1\xa1\xa1\xa1", "\xa1\xa0\xa0\xa0\xa1", "\xa1\xa0\xa1\xa0\xa1", "\xa1\xa0\xa0\xa0\xa1", "\xa1\xa1\xa1\xa1\xa1" ); $yStart = $oy-2; $xStart = $ox-2; for($y=0; $y<5; $y++) { self::set($frame, $xStart, $yStart+$y, $finder[$y]); } }
[ "public", "static", "function", "putAlignmentMarker", "(", "array", "&", "$", "frame", ",", "$", "ox", ",", "$", "oy", ")", "{", "$", "finder", "=", "array", "(", "\"\\xa1\\xa1\\xa1\\xa1\\xa1\"", ",", "\"\\xa1\\xa0\\xa0\\xa0\\xa1\"", ",", "\"\\xa1\\xa0\\xa1\\xa0\\xa1\"", ",", "\"\\xa1\\xa0\\xa0\\xa0\\xa1\"", ",", "\"\\xa1\\xa1\\xa1\\xa1\\xa1\"", ")", ";", "$", "yStart", "=", "$", "oy", "-", "2", ";", "$", "xStart", "=", "$", "ox", "-", "2", ";", "for", "(", "$", "y", "=", "0", ";", "$", "y", "<", "5", ";", "$", "y", "++", ")", "{", "self", "::", "set", "(", "$", "frame", ",", "$", "xStart", ",", "$", "yStart", "+", "$", "y", ",", "$", "finder", "[", "$", "y", "]", ")", ";", "}", "}" ]
Puts an alignment marker. @param frame @param width @param ox,oy center coordinate of the pattern
[ "Puts", "an", "alignment", "marker", "." ]
9988012930e9c2c20c5f8de4883ab010b674090b
https://github.com/ziplr/php-qr-code/blob/9988012930e9c2c20c5f8de4883ab010b674090b/src/qrspec.php#L330-L346
37,678
ziplr/php-qr-code
src/qrspec.php
QRspec.putFinderPattern
public static function putFinderPattern(&$frame, $ox, $oy) { $finder = array( "\xc1\xc1\xc1\xc1\xc1\xc1\xc1", "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", "\xc1\xc1\xc1\xc1\xc1\xc1\xc1" ); for($y=0; $y<7; $y++) { self::set($frame, $ox, $oy+$y, $finder[$y]); } }
php
public static function putFinderPattern(&$frame, $ox, $oy) { $finder = array( "\xc1\xc1\xc1\xc1\xc1\xc1\xc1", "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", "\xc1\xc0\xc1\xc1\xc1\xc0\xc1", "\xc1\xc0\xc0\xc0\xc0\xc0\xc1", "\xc1\xc1\xc1\xc1\xc1\xc1\xc1" ); for($y=0; $y<7; $y++) { self::set($frame, $ox, $oy+$y, $finder[$y]); } }
[ "public", "static", "function", "putFinderPattern", "(", "&", "$", "frame", ",", "$", "ox", ",", "$", "oy", ")", "{", "$", "finder", "=", "array", "(", "\"\\xc1\\xc1\\xc1\\xc1\\xc1\\xc1\\xc1\"", ",", "\"\\xc1\\xc0\\xc0\\xc0\\xc0\\xc0\\xc1\"", ",", "\"\\xc1\\xc0\\xc1\\xc1\\xc1\\xc0\\xc1\"", ",", "\"\\xc1\\xc0\\xc1\\xc1\\xc1\\xc0\\xc1\"", ",", "\"\\xc1\\xc0\\xc1\\xc1\\xc1\\xc0\\xc1\"", ",", "\"\\xc1\\xc0\\xc0\\xc0\\xc0\\xc0\\xc1\"", ",", "\"\\xc1\\xc1\\xc1\\xc1\\xc1\\xc1\\xc1\"", ")", ";", "for", "(", "$", "y", "=", "0", ";", "$", "y", "<", "7", ";", "$", "y", "++", ")", "{", "self", "::", "set", "(", "$", "frame", ",", "$", "ox", ",", "$", "oy", "+", "$", "y", ",", "$", "finder", "[", "$", "y", "]", ")", ";", "}", "}" ]
Put a finder pattern. @param frame @param width @param ox,oy upper-left coordinate of the pattern \hideinitializer
[ "Put", "a", "finder", "pattern", "." ]
9988012930e9c2c20c5f8de4883ab010b674090b
https://github.com/ziplr/php-qr-code/blob/9988012930e9c2c20c5f8de4883ab010b674090b/src/qrspec.php#L445-L460
37,679
ziplr/php-qr-code
src/qrspec.php
QRspec.debug
public static function debug($frame, $binary_mode = false) { if ($binary_mode) { foreach ($frame as &$frameLine) { $frameLine = join('<span class="m">&nbsp;&nbsp;</span>', explode('0', $frameLine)); $frameLine = join('&#9608;&#9608;', explode('1', $frameLine)); } echo '<style> .m { background-color: white; } </style> '; echo '<pre><tt><br/ ><br/ ><br/ >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; echo join("<br/ >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", $frame); echo '</tt></pre><br/ ><br/ ><br/ ><br/ ><br/ ><br/ >'; } else { foreach ($frame as &$frameLine) { $frameLine = strtr($frameLine, array( "\xc0" => '<span class="m">&nbsp;</span>', //marker 0 "\xc1" => '<span class="m">&#9618;</span>', //marker 1 "\xa0" => '<span class="p">&nbsp;</span>', //submarker 0 "\xa1" => '<span class="p">&#9618;</span>', //submarker 1 "\x84" => '<span class="s">F</span>', //format 0 "\x85" => '<span class="s">f</span>', //format 1 "\x81" => '<span class="x">S</span>', //special bit "\x90" => '<span class="c">C</span>', //clock 0 "\x91" => '<span class="c">c</span>', //clock 1 "\x88" => '<span class="f">&nbsp;</span>', //version 0 "\x89" => '<span class="f">&#9618;</span>', //version 1 "\x03" => '1', // 1 "\x02" => '0', // 0 )); } echo '<style>'; echo ' .p { background-color: yellow; }'; echo ' .m { background-color: #00FF00; }'; echo ' .s { background-color: #FF0000; }'; echo ' .c { background-color: aqua; }'; echo ' .x { background-color: pink; }'; echo ' .f { background-color: gold; }'; echo '</style>'; echo "<tt>"; echo join("<br/ >", $frame); echo "<br/>Legend:<br/>"; echo '1 - data 1<br/>'; echo '0 - data 0<br/>'; echo '<span class="m">&nbsp;</span> - marker bit 0<br/>'; echo '<span class="m">&#9618;</span> - marker bit 1<br/>'; echo '<span class="p">&nbsp;</span> - secondary marker bit 0<br/>'; echo '<span class="p">&#9618;</span> - secondary marker bit 1<br/>'; echo '<span class="s">F</span> - format bit 0<br/>'; echo '<span class="s">f</span> - format bit 1<br/>'; echo '<span class="x">S</span> - special bit<br/>'; echo '<span class="c">C</span> - clock bit 0<br/>'; echo '<span class="c">c</span> - clock bit 1<br/>'; echo '<span class="f">&nbsp;</span> - version bit 0<br/>'; echo '<span class="f">&#9618;</span> - version bit 1<br/>'; echo "</tt>"; } }
php
public static function debug($frame, $binary_mode = false) { if ($binary_mode) { foreach ($frame as &$frameLine) { $frameLine = join('<span class="m">&nbsp;&nbsp;</span>', explode('0', $frameLine)); $frameLine = join('&#9608;&#9608;', explode('1', $frameLine)); } echo '<style> .m { background-color: white; } </style> '; echo '<pre><tt><br/ ><br/ ><br/ >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; echo join("<br/ >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", $frame); echo '</tt></pre><br/ ><br/ ><br/ ><br/ ><br/ ><br/ >'; } else { foreach ($frame as &$frameLine) { $frameLine = strtr($frameLine, array( "\xc0" => '<span class="m">&nbsp;</span>', //marker 0 "\xc1" => '<span class="m">&#9618;</span>', //marker 1 "\xa0" => '<span class="p">&nbsp;</span>', //submarker 0 "\xa1" => '<span class="p">&#9618;</span>', //submarker 1 "\x84" => '<span class="s">F</span>', //format 0 "\x85" => '<span class="s">f</span>', //format 1 "\x81" => '<span class="x">S</span>', //special bit "\x90" => '<span class="c">C</span>', //clock 0 "\x91" => '<span class="c">c</span>', //clock 1 "\x88" => '<span class="f">&nbsp;</span>', //version 0 "\x89" => '<span class="f">&#9618;</span>', //version 1 "\x03" => '1', // 1 "\x02" => '0', // 0 )); } echo '<style>'; echo ' .p { background-color: yellow; }'; echo ' .m { background-color: #00FF00; }'; echo ' .s { background-color: #FF0000; }'; echo ' .c { background-color: aqua; }'; echo ' .x { background-color: pink; }'; echo ' .f { background-color: gold; }'; echo '</style>'; echo "<tt>"; echo join("<br/ >", $frame); echo "<br/>Legend:<br/>"; echo '1 - data 1<br/>'; echo '0 - data 0<br/>'; echo '<span class="m">&nbsp;</span> - marker bit 0<br/>'; echo '<span class="m">&#9618;</span> - marker bit 1<br/>'; echo '<span class="p">&nbsp;</span> - secondary marker bit 0<br/>'; echo '<span class="p">&#9618;</span> - secondary marker bit 1<br/>'; echo '<span class="s">F</span> - format bit 0<br/>'; echo '<span class="s">f</span> - format bit 1<br/>'; echo '<span class="x">S</span> - special bit<br/>'; echo '<span class="c">C</span> - clock bit 0<br/>'; echo '<span class="c">c</span> - clock bit 1<br/>'; echo '<span class="f">&nbsp;</span> - version bit 0<br/>'; echo '<span class="f">&#9618;</span> - version bit 1<br/>'; echo "</tt>"; } }
[ "public", "static", "function", "debug", "(", "$", "frame", ",", "$", "binary_mode", "=", "false", ")", "{", "if", "(", "$", "binary_mode", ")", "{", "foreach", "(", "$", "frame", "as", "&", "$", "frameLine", ")", "{", "$", "frameLine", "=", "join", "(", "'<span class=\"m\">&nbsp;&nbsp;</span>'", ",", "explode", "(", "'0'", ",", "$", "frameLine", ")", ")", ";", "$", "frameLine", "=", "join", "(", "'&#9608;&#9608;'", ",", "explode", "(", "'1'", ",", "$", "frameLine", ")", ")", ";", "}", "echo", "'<style> .m { background-color: white; } </style> '", ";", "echo", "'<pre><tt><br/ ><br/ ><br/ >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'", ";", "echo", "join", "(", "\"<br/ >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\"", ",", "$", "frame", ")", ";", "echo", "'</tt></pre><br/ ><br/ ><br/ ><br/ ><br/ ><br/ >'", ";", "}", "else", "{", "foreach", "(", "$", "frame", "as", "&", "$", "frameLine", ")", "{", "$", "frameLine", "=", "strtr", "(", "$", "frameLine", ",", "array", "(", "\"\\xc0\"", "=>", "'<span class=\"m\">&nbsp;</span>'", ",", "//marker 0 ", "\"\\xc1\"", "=>", "'<span class=\"m\">&#9618;</span>'", ",", "//marker 1", "\"\\xa0\"", "=>", "'<span class=\"p\">&nbsp;</span>'", ",", "//submarker 0", "\"\\xa1\"", "=>", "'<span class=\"p\">&#9618;</span>'", ",", "//submarker 1", "\"\\x84\"", "=>", "'<span class=\"s\">F</span>'", ",", "//format 0", "\"\\x85\"", "=>", "'<span class=\"s\">f</span>'", ",", "//format 1", "\"\\x81\"", "=>", "'<span class=\"x\">S</span>'", ",", "//special bit", "\"\\x90\"", "=>", "'<span class=\"c\">C</span>'", ",", "//clock 0", "\"\\x91\"", "=>", "'<span class=\"c\">c</span>'", ",", "//clock 1", "\"\\x88\"", "=>", "'<span class=\"f\">&nbsp;</span>'", ",", "//version 0 ", "\"\\x89\"", "=>", "'<span class=\"f\">&#9618;</span>'", ",", "//version 1", "\"\\x03\"", "=>", "'1'", ",", "// 1", "\"\\x02\"", "=>", "'0'", ",", "// 0 ", ")", ")", ";", "}", "echo", "'<style>'", ";", "echo", "' .p { background-color: yellow; }'", ";", "echo", "' .m { background-color: #00FF00; }'", ";", "echo", "' .s { background-color: #FF0000; }'", ";", "echo", "' .c { background-color: aqua; }'", ";", "echo", "' .x { background-color: pink; }'", ";", "echo", "' .f { background-color: gold; }'", ";", "echo", "'</style>'", ";", "echo", "\"<tt>\"", ";", "echo", "join", "(", "\"<br/ >\"", ",", "$", "frame", ")", ";", "echo", "\"<br/>Legend:<br/>\"", ";", "echo", "'1 - data 1<br/>'", ";", "echo", "'0 - data 0<br/>'", ";", "echo", "'<span class=\"m\">&nbsp;</span> - marker bit 0<br/>'", ";", "echo", "'<span class=\"m\">&#9618;</span> - marker bit 1<br/>'", ";", "echo", "'<span class=\"p\">&nbsp;</span> - secondary marker bit 0<br/>'", ";", "echo", "'<span class=\"p\">&#9618;</span> - secondary marker bit 1<br/>'", ";", "echo", "'<span class=\"s\">F</span> - format bit 0<br/>'", ";", "echo", "'<span class=\"s\">f</span> - format bit 1<br/>'", ";", "echo", "'<span class=\"x\">S</span> - special bit<br/>'", ";", "echo", "'<span class=\"c\">C</span> - clock bit 0<br/>'", ";", "echo", "'<span class=\"c\">c</span> - clock bit 1<br/>'", ";", "echo", "'<span class=\"f\">&nbsp;</span> - version bit 0<br/>'", ";", "echo", "'<span class=\"f\">&#9618;</span> - version bit 1<br/>'", ";", "echo", "\"</tt>\"", ";", "}", "}" ]
Dumps debug HTML of frame. @param Array $frame code frame @param Boolean $binary_mode in binary mode only contents is dumped, without styling
[ "Dumps", "debug", "HTML", "of", "frame", "." ]
9988012930e9c2c20c5f8de4883ab010b674090b
https://github.com/ziplr/php-qr-code/blob/9988012930e9c2c20c5f8de4883ab010b674090b/src/qrspec.php#L545-L608
37,680
ziplr/php-qr-code
src/qrspec.php
QRspec.set
public static function set(&$frame, $x, $y, $repl, $replLen = false) { $frame[$y] = substr_replace($frame[$y], ($replLen !== false)?substr($repl,0,$replLen):$repl, $x, ($replLen !== false)?$replLen:strlen($repl)); }
php
public static function set(&$frame, $x, $y, $repl, $replLen = false) { $frame[$y] = substr_replace($frame[$y], ($replLen !== false)?substr($repl,0,$replLen):$repl, $x, ($replLen !== false)?$replLen:strlen($repl)); }
[ "public", "static", "function", "set", "(", "&", "$", "frame", ",", "$", "x", ",", "$", "y", ",", "$", "repl", ",", "$", "replLen", "=", "false", ")", "{", "$", "frame", "[", "$", "y", "]", "=", "substr_replace", "(", "$", "frame", "[", "$", "y", "]", ",", "(", "$", "replLen", "!==", "false", ")", "?", "substr", "(", "$", "repl", ",", "0", ",", "$", "replLen", ")", ":", "$", "repl", ",", "$", "x", ",", "(", "$", "replLen", "!==", "false", ")", "?", "$", "replLen", ":", "strlen", "(", "$", "repl", ")", ")", ";", "}" ]
Sets code frame with speciffied code. @param Array $frame target frame (modified by reference) @param Integer $x X-axis position of replacement @param Integer $y Y-axis position of replacement @param Byte $repl replacement string @param Integer $replLen (optional) replacement string length, when __Integer__ > 1 subset of given $repl is used, when __false__ whole $repl is used
[ "Sets", "code", "frame", "with", "speciffied", "code", "." ]
9988012930e9c2c20c5f8de4883ab010b674090b
https://github.com/ziplr/php-qr-code/blob/9988012930e9c2c20c5f8de4883ab010b674090b/src/qrspec.php#L668-L670
37,681
czim/laravel-filter
src/Filter.php
Filter.setting
public function setting($key) { return isset($this->settings[$key]) ? $this->settings[$key] : null; }
php
public function setting($key) { return isset($this->settings[$key]) ? $this->settings[$key] : null; }
[ "public", "function", "setting", "(", "$", "key", ")", "{", "return", "isset", "(", "$", "this", "->", "settings", "[", "$", "key", "]", ")", "?", "$", "this", "->", "settings", "[", "$", "key", "]", ":", "null", ";", "}" ]
Getter for global settings @param $key @return mixed|null
[ "Getter", "for", "global", "settings" ]
670857a5c51a4e3d4de45779cc6fc1d82667042a
https://github.com/czim/laravel-filter/blob/670857a5c51a4e3d4de45779cc6fc1d82667042a/src/Filter.php#L143-L146
37,682
czim/laravel-filter
src/Filter.php
Filter.applyParameters
protected function applyParameters($query) { $this->storeGlobalSettings(); $strategies = $this->buildStrategies(); foreach ($this->data->getApplicableAttributes() as $parameterName) { // should we skip it no matter what? if ($this->isParameterIgnored($parameterName)) continue; // get the value for the filter parameter // and if it is empty, we're not filtering by it and should skip it $parameterValue = $this->data->getParameterValue($parameterName); if ($this->isParameterValueUnset($parameterName, $parameterValue)) continue; // find the strategy to be used for applying the filter for this parameter // then normalize the strategy so that we can call_user_func on it $strategy = isset($strategies[$parameterName]) ? $strategies[$parameterName] : null; // is it a global setting, not a normal parameter? skip it if ($strategy === static::SETTING) continue; if (is_a($strategy, ParameterFilterInterface::class)) { $strategy = [ $strategy, 'apply' ]; } elseif (is_null($strategy)) { // default, let it be handled by applyParameter $strategy = [ $this, 'applyParameter' ]; } elseif ( ! is_callable($strategy) && ! is_array($strategy)) { throw new ParameterStrategyInvalidException( "Invalid strategy defined for parameter '{$parameterName}'," . " must be ParameterFilterInterface, classname, callable or null" ); } // apply the strategy call_user_func_array($strategy, [ $parameterName, $parameterValue, $query, $this ]); } }
php
protected function applyParameters($query) { $this->storeGlobalSettings(); $strategies = $this->buildStrategies(); foreach ($this->data->getApplicableAttributes() as $parameterName) { // should we skip it no matter what? if ($this->isParameterIgnored($parameterName)) continue; // get the value for the filter parameter // and if it is empty, we're not filtering by it and should skip it $parameterValue = $this->data->getParameterValue($parameterName); if ($this->isParameterValueUnset($parameterName, $parameterValue)) continue; // find the strategy to be used for applying the filter for this parameter // then normalize the strategy so that we can call_user_func on it $strategy = isset($strategies[$parameterName]) ? $strategies[$parameterName] : null; // is it a global setting, not a normal parameter? skip it if ($strategy === static::SETTING) continue; if (is_a($strategy, ParameterFilterInterface::class)) { $strategy = [ $strategy, 'apply' ]; } elseif (is_null($strategy)) { // default, let it be handled by applyParameter $strategy = [ $this, 'applyParameter' ]; } elseif ( ! is_callable($strategy) && ! is_array($strategy)) { throw new ParameterStrategyInvalidException( "Invalid strategy defined for parameter '{$parameterName}'," . " must be ParameterFilterInterface, classname, callable or null" ); } // apply the strategy call_user_func_array($strategy, [ $parameterName, $parameterValue, $query, $this ]); } }
[ "protected", "function", "applyParameters", "(", "$", "query", ")", "{", "$", "this", "->", "storeGlobalSettings", "(", ")", ";", "$", "strategies", "=", "$", "this", "->", "buildStrategies", "(", ")", ";", "foreach", "(", "$", "this", "->", "data", "->", "getApplicableAttributes", "(", ")", "as", "$", "parameterName", ")", "{", "// should we skip it no matter what?", "if", "(", "$", "this", "->", "isParameterIgnored", "(", "$", "parameterName", ")", ")", "continue", ";", "// get the value for the filter parameter", "// and if it is empty, we're not filtering by it and should skip it", "$", "parameterValue", "=", "$", "this", "->", "data", "->", "getParameterValue", "(", "$", "parameterName", ")", ";", "if", "(", "$", "this", "->", "isParameterValueUnset", "(", "$", "parameterName", ",", "$", "parameterValue", ")", ")", "continue", ";", "// find the strategy to be used for applying the filter for this parameter", "// then normalize the strategy so that we can call_user_func on it", "$", "strategy", "=", "isset", "(", "$", "strategies", "[", "$", "parameterName", "]", ")", "?", "$", "strategies", "[", "$", "parameterName", "]", ":", "null", ";", "// is it a global setting, not a normal parameter? skip it", "if", "(", "$", "strategy", "===", "static", "::", "SETTING", ")", "continue", ";", "if", "(", "is_a", "(", "$", "strategy", ",", "ParameterFilterInterface", "::", "class", ")", ")", "{", "$", "strategy", "=", "[", "$", "strategy", ",", "'apply'", "]", ";", "}", "elseif", "(", "is_null", "(", "$", "strategy", ")", ")", "{", "// default, let it be handled by applyParameter", "$", "strategy", "=", "[", "$", "this", ",", "'applyParameter'", "]", ";", "}", "elseif", "(", "!", "is_callable", "(", "$", "strategy", ")", "&&", "!", "is_array", "(", "$", "strategy", ")", ")", "{", "throw", "new", "ParameterStrategyInvalidException", "(", "\"Invalid strategy defined for parameter '{$parameterName}',\"", ".", "\" must be ParameterFilterInterface, classname, callable or null\"", ")", ";", "}", "// apply the strategy", "call_user_func_array", "(", "$", "strategy", ",", "[", "$", "parameterName", ",", "$", "parameterValue", ",", "$", "query", ",", "$", "this", "]", ")", ";", "}", "}" ]
Applies all filter parameters to the query, using the configured strategies @param Model|EloquentBuilder $query @throws ParameterStrategyInvalidException
[ "Applies", "all", "filter", "parameters", "to", "the", "query", "using", "the", "configured", "strategies" ]
670857a5c51a4e3d4de45779cc6fc1d82667042a
https://github.com/czim/laravel-filter/blob/670857a5c51a4e3d4de45779cc6fc1d82667042a/src/Filter.php#L183-L230
37,683
czim/laravel-filter
src/Filter.php
Filter.storeGlobalSettings
protected function storeGlobalSettings() { foreach ($this->strategies as $setting => &$strategy) { if ( ! is_string($strategy) || $strategy !== static::SETTING) continue; $this->settings[ $setting ] = $this->parameterValue($setting); } }
php
protected function storeGlobalSettings() { foreach ($this->strategies as $setting => &$strategy) { if ( ! is_string($strategy) || $strategy !== static::SETTING) continue; $this->settings[ $setting ] = $this->parameterValue($setting); } }
[ "protected", "function", "storeGlobalSettings", "(", ")", "{", "foreach", "(", "$", "this", "->", "strategies", "as", "$", "setting", "=>", "&", "$", "strategy", ")", "{", "if", "(", "!", "is_string", "(", "$", "strategy", ")", "||", "$", "strategy", "!==", "static", "::", "SETTING", ")", "continue", ";", "$", "this", "->", "settings", "[", "$", "setting", "]", "=", "$", "this", "->", "parameterValue", "(", "$", "setting", ")", ";", "}", "}" ]
Interprets parameters with the SETTING string and stores their current values in the settings property. This must be done before the parameters are applied, if the settings are to have any effect Note that you must add your own interpretation & effect for settings in your FilterParameter methods/classes (use the setting() getter)
[ "Interprets", "parameters", "with", "the", "SETTING", "string", "and", "stores", "their", "current", "values", "in", "the", "settings", "property", ".", "This", "must", "be", "done", "before", "the", "parameters", "are", "applied", "if", "the", "settings", "are", "to", "have", "any", "effect" ]
670857a5c51a4e3d4de45779cc6fc1d82667042a
https://github.com/czim/laravel-filter/blob/670857a5c51a4e3d4de45779cc6fc1d82667042a/src/Filter.php#L296-L304
37,684
czim/laravel-filter
src/Filter.php
Filter.addJoin
public function addJoin($key, array $parameters, $joinType = null) { if ( ! is_null($joinType)) { if ($joinType == 'join' || stripos($joinType, 'inner') !== false) { $this->joinTypes[$key] = 'join'; } elseif (stripos($joinType, 'right') !== false) { $this->joinTypes[$key] = 'rightJoin'; } else { unset( $this->joinTypes[$key] ); } } $this->joins[$key] = $parameters; return $this; }
php
public function addJoin($key, array $parameters, $joinType = null) { if ( ! is_null($joinType)) { if ($joinType == 'join' || stripos($joinType, 'inner') !== false) { $this->joinTypes[$key] = 'join'; } elseif (stripos($joinType, 'right') !== false) { $this->joinTypes[$key] = 'rightJoin'; } else { unset( $this->joinTypes[$key] ); } } $this->joins[$key] = $parameters; return $this; }
[ "public", "function", "addJoin", "(", "$", "key", ",", "array", "$", "parameters", ",", "$", "joinType", "=", "null", ")", "{", "if", "(", "!", "is_null", "(", "$", "joinType", ")", ")", "{", "if", "(", "$", "joinType", "==", "'join'", "||", "stripos", "(", "$", "joinType", ",", "'inner'", ")", "!==", "false", ")", "{", "$", "this", "->", "joinTypes", "[", "$", "key", "]", "=", "'join'", ";", "}", "elseif", "(", "stripos", "(", "$", "joinType", ",", "'right'", ")", "!==", "false", ")", "{", "$", "this", "->", "joinTypes", "[", "$", "key", "]", "=", "'rightJoin'", ";", "}", "else", "{", "unset", "(", "$", "this", "->", "joinTypes", "[", "$", "key", "]", ")", ";", "}", "}", "$", "this", "->", "joins", "[", "$", "key", "]", "=", "$", "parameters", ";", "return", "$", "this", ";", "}" ]
Adds a query join to be added after all parameters are applied @param string $key identifying key, used to prevent duplicates @param array $parameters @param string $joinType 'inner', 'right', defaults to left join @return $this
[ "Adds", "a", "query", "join", "to", "be", "added", "after", "all", "parameters", "are", "applied" ]
670857a5c51a4e3d4de45779cc6fc1d82667042a
https://github.com/czim/laravel-filter/blob/670857a5c51a4e3d4de45779cc6fc1d82667042a/src/Filter.php#L339-L355
37,685
czim/laravel-filter
src/Filter.php
Filter.applyJoins
protected function applyJoins($query) { foreach ($this->joins as $key => $join) { if (isset($this->joinTypes[$key])) { $joinMethod = $this->joinTypes[$key]; } else { $joinMethod = 'leftJoin'; } call_user_func_array([ $query, $joinMethod ], $join); } }
php
protected function applyJoins($query) { foreach ($this->joins as $key => $join) { if (isset($this->joinTypes[$key])) { $joinMethod = $this->joinTypes[$key]; } else { $joinMethod = 'leftJoin'; } call_user_func_array([ $query, $joinMethod ], $join); } }
[ "protected", "function", "applyJoins", "(", "$", "query", ")", "{", "foreach", "(", "$", "this", "->", "joins", "as", "$", "key", "=>", "$", "join", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "joinTypes", "[", "$", "key", "]", ")", ")", "{", "$", "joinMethod", "=", "$", "this", "->", "joinTypes", "[", "$", "key", "]", ";", "}", "else", "{", "$", "joinMethod", "=", "'leftJoin'", ";", "}", "call_user_func_array", "(", "[", "$", "query", ",", "$", "joinMethod", "]", ",", "$", "join", ")", ";", "}", "}" ]
Applies joins to the filter-based query @param EloquentBuilder $query
[ "Applies", "joins", "to", "the", "filter", "-", "based", "query" ]
670857a5c51a4e3d4de45779cc6fc1d82667042a
https://github.com/czim/laravel-filter/blob/670857a5c51a4e3d4de45779cc6fc1d82667042a/src/Filter.php#L362-L374
37,686
czim/laravel-filter
src/Filter.php
Filter.isParameterIgnored
protected function isParameterIgnored($parameterName) { if (empty($this->ignoreParameters)) return false; return (array_search($parameterName, $this->ignoreParameters) !== false); }
php
protected function isParameterIgnored($parameterName) { if (empty($this->ignoreParameters)) return false; return (array_search($parameterName, $this->ignoreParameters) !== false); }
[ "protected", "function", "isParameterIgnored", "(", "$", "parameterName", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "ignoreParameters", ")", ")", "return", "false", ";", "return", "(", "array_search", "(", "$", "parameterName", ",", "$", "this", "->", "ignoreParameters", ")", "!==", "false", ")", ";", "}" ]
Returns whether a parameter name is currently on the ignore list @param $parameterName @return bool
[ "Returns", "whether", "a", "parameter", "name", "is", "currently", "on", "the", "ignore", "list" ]
670857a5c51a4e3d4de45779cc6fc1d82667042a
https://github.com/czim/laravel-filter/blob/670857a5c51a4e3d4de45779cc6fc1d82667042a/src/Filter.php#L414-L419
37,687
czim/laravel-filter
src/Traits/Validatable.php
Validatable.validate
public function validate() { $this->validator = Validator::make($this->getAttributes(), $this->getRules()); return ! $this->validator->fails(); }
php
public function validate() { $this->validator = Validator::make($this->getAttributes(), $this->getRules()); return ! $this->validator->fails(); }
[ "public", "function", "validate", "(", ")", "{", "$", "this", "->", "validator", "=", "Validator", "::", "make", "(", "$", "this", "->", "getAttributes", "(", ")", ",", "$", "this", "->", "getRules", "(", ")", ")", ";", "return", "!", "$", "this", "->", "validator", "->", "fails", "(", ")", ";", "}" ]
Validates the filter data @return boolean
[ "Validates", "the", "filter", "data" ]
670857a5c51a4e3d4de45779cc6fc1d82667042a
https://github.com/czim/laravel-filter/blob/670857a5c51a4e3d4de45779cc6fc1d82667042a/src/Traits/Validatable.php#L30-L35
37,688
czim/laravel-filter
src/ParameterCounters/SimpleDistinctValue.php
SimpleDistinctValue.count
public function count($name, $query, CountableFilterInterface $filter) { // if the columnname is not set, assume an id field based on a table name $columnName = (empty($this->columnName)) ? $name : $this->columnName; if ( ! $this->includeEmpty) { $query->whereNotNull($columnName); } return $query->select( "{$columnName} AS {$this->columnAlias}", DB::raw("{$this->countRaw} AS {$this->countAlias}") ) ->groupBy($columnName) ->pluck($this->countAlias, $this->columnAlias); }
php
public function count($name, $query, CountableFilterInterface $filter) { // if the columnname is not set, assume an id field based on a table name $columnName = (empty($this->columnName)) ? $name : $this->columnName; if ( ! $this->includeEmpty) { $query->whereNotNull($columnName); } return $query->select( "{$columnName} AS {$this->columnAlias}", DB::raw("{$this->countRaw} AS {$this->countAlias}") ) ->groupBy($columnName) ->pluck($this->countAlias, $this->columnAlias); }
[ "public", "function", "count", "(", "$", "name", ",", "$", "query", ",", "CountableFilterInterface", "$", "filter", ")", "{", "// if the columnname is not set, assume an id field based on a table name", "$", "columnName", "=", "(", "empty", "(", "$", "this", "->", "columnName", ")", ")", "?", "$", "name", ":", "$", "this", "->", "columnName", ";", "if", "(", "!", "$", "this", "->", "includeEmpty", ")", "{", "$", "query", "->", "whereNotNull", "(", "$", "columnName", ")", ";", "}", "return", "$", "query", "->", "select", "(", "\"{$columnName} AS {$this->columnAlias}\"", ",", "DB", "::", "raw", "(", "\"{$this->countRaw} AS {$this->countAlias}\"", ")", ")", "->", "groupBy", "(", "$", "columnName", ")", "->", "pluck", "(", "$", "this", "->", "countAlias", ",", "$", "this", "->", "columnAlias", ")", ";", "}" ]
Returns the count for a countable parameter, given the query provided @param string $name @param EloquentBuilder $query @param CountableFilterInterface $filter @return array
[ "Returns", "the", "count", "for", "a", "countable", "parameter", "given", "the", "query", "provided" ]
670857a5c51a4e3d4de45779cc6fc1d82667042a
https://github.com/czim/laravel-filter/blob/670857a5c51a4e3d4de45779cc6fc1d82667042a/src/ParameterCounters/SimpleDistinctValue.php#L63-L80
37,689
czim/laravel-filter
src/FilterData.php
FilterData.getParameterValue
public function getParameterValue($name) { return (isset($this->attributes[$name])) ? $this->attributes[$name] : null; }
php
public function getParameterValue($name) { return (isset($this->attributes[$name])) ? $this->attributes[$name] : null; }
[ "public", "function", "getParameterValue", "(", "$", "name", ")", "{", "return", "(", "isset", "(", "$", "this", "->", "attributes", "[", "$", "name", "]", ")", ")", "?", "$", "this", "->", "attributes", "[", "$", "name", "]", ":", "null", ";", "}" ]
Gets the value for a parameter @param $name @return mixed
[ "Gets", "the", "value", "for", "a", "parameter" ]
670857a5c51a4e3d4de45779cc6fc1d82667042a
https://github.com/czim/laravel-filter/blob/670857a5c51a4e3d4de45779cc6fc1d82667042a/src/FilterData.php#L151-L154
37,690
artkost/yii2-qa
actions/VoteAction.php
VoteAction.entityVote
protected function entityVote($model, $type, $partial = 'parts/vote', $format = 'json') { $data = ['status' => false]; if ($model && Vote::isUserCan($model, Yii::$app->user->id)) { $data = [ 'status' => true, 'html' => $this->controller->renderPartial($partial, ['model' => Vote::process($model, $type)]) ]; } if (Yii::$app->request->isAjax) { return new Response([ 'data' => $data, 'format' => $format ]); } return $this->controller->redirect([$this->viewRoute, 'id' => $model['id']]); }
php
protected function entityVote($model, $type, $partial = 'parts/vote', $format = 'json') { $data = ['status' => false]; if ($model && Vote::isUserCan($model, Yii::$app->user->id)) { $data = [ 'status' => true, 'html' => $this->controller->renderPartial($partial, ['model' => Vote::process($model, $type)]) ]; } if (Yii::$app->request->isAjax) { return new Response([ 'data' => $data, 'format' => $format ]); } return $this->controller->redirect([$this->viewRoute, 'id' => $model['id']]); }
[ "protected", "function", "entityVote", "(", "$", "model", ",", "$", "type", ",", "$", "partial", "=", "'parts/vote'", ",", "$", "format", "=", "'json'", ")", "{", "$", "data", "=", "[", "'status'", "=>", "false", "]", ";", "if", "(", "$", "model", "&&", "Vote", "::", "isUserCan", "(", "$", "model", ",", "Yii", "::", "$", "app", "->", "user", "->", "id", ")", ")", "{", "$", "data", "=", "[", "'status'", "=>", "true", ",", "'html'", "=>", "$", "this", "->", "controller", "->", "renderPartial", "(", "$", "partial", ",", "[", "'model'", "=>", "Vote", "::", "process", "(", "$", "model", ",", "$", "type", ")", "]", ")", "]", ";", "}", "if", "(", "Yii", "::", "$", "app", "->", "request", "->", "isAjax", ")", "{", "return", "new", "Response", "(", "[", "'data'", "=>", "$", "data", ",", "'format'", "=>", "$", "format", "]", ")", ";", "}", "return", "$", "this", "->", "controller", "->", "redirect", "(", "[", "$", "this", "->", "viewRoute", ",", "'id'", "=>", "$", "model", "[", "'id'", "]", "]", ")", ";", "}" ]
Increment or decrement votes of model by given type @param ActiveRecord $model @param string $type can be 'up' or 'down' @param string $partial template name @param string $format @return Response
[ "Increment", "or", "decrement", "votes", "of", "model", "by", "given", "type" ]
678765232c8b9a45be9a08c17c13c1a4acfd3d20
https://github.com/artkost/yii2-qa/blob/678765232c8b9a45be9a08c17c13c1a4acfd3d20/actions/VoteAction.php#L35-L54
37,691
artkost/yii2-qa
models/Vote.php
Vote.isUserCan
public static function isUserCan($model, $userId) { //if he try vote on its own question if (isset($model['user_id']) && $model['user_id'] == $userId) { return false; } else { return !self::find()->where([ 'user_id' => $userId, 'entity' => self::modelEntityType($model), 'entity_id' => $model['id'] ])->exists(); } }
php
public static function isUserCan($model, $userId) { //if he try vote on its own question if (isset($model['user_id']) && $model['user_id'] == $userId) { return false; } else { return !self::find()->where([ 'user_id' => $userId, 'entity' => self::modelEntityType($model), 'entity_id' => $model['id'] ])->exists(); } }
[ "public", "static", "function", "isUserCan", "(", "$", "model", ",", "$", "userId", ")", "{", "//if he try vote on its own question", "if", "(", "isset", "(", "$", "model", "[", "'user_id'", "]", ")", "&&", "$", "model", "[", "'user_id'", "]", "==", "$", "userId", ")", "{", "return", "false", ";", "}", "else", "{", "return", "!", "self", "::", "find", "(", ")", "->", "where", "(", "[", "'user_id'", "=>", "$", "userId", ",", "'entity'", "=>", "self", "::", "modelEntityType", "(", "$", "model", ")", ",", "'entity_id'", "=>", "$", "model", "[", "'id'", "]", "]", ")", "->", "exists", "(", ")", ";", "}", "}" ]
Check if current user has access to vote @param ActiveRecord $model @param int $userId @return bool
[ "Check", "if", "current", "user", "has", "access", "to", "vote" ]
678765232c8b9a45be9a08c17c13c1a4acfd3d20
https://github.com/artkost/yii2-qa/blob/678765232c8b9a45be9a08c17c13c1a4acfd3d20/models/Vote.php#L49-L61
37,692
artkost/yii2-qa
models/Vote.php
Vote.modelEntityType
protected static function modelEntityType($model) { if ($model instanceof QuestionInterface) { return self::ENTITY_QUESTION; } elseif ($model instanceof AnswerInterface) { return self::ENTITY_ANSWER; } else { $className = get_class($model); throw new UnknownClassException("Model class '{$className}' not supported"); } }
php
protected static function modelEntityType($model) { if ($model instanceof QuestionInterface) { return self::ENTITY_QUESTION; } elseif ($model instanceof AnswerInterface) { return self::ENTITY_ANSWER; } else { $className = get_class($model); throw new UnknownClassException("Model class '{$className}' not supported"); } }
[ "protected", "static", "function", "modelEntityType", "(", "$", "model", ")", "{", "if", "(", "$", "model", "instanceof", "QuestionInterface", ")", "{", "return", "self", "::", "ENTITY_QUESTION", ";", "}", "elseif", "(", "$", "model", "instanceof", "AnswerInterface", ")", "{", "return", "self", "::", "ENTITY_ANSWER", ";", "}", "else", "{", "$", "className", "=", "get_class", "(", "$", "model", ")", ";", "throw", "new", "UnknownClassException", "(", "\"Model class '{$className}' not supported\"", ")", ";", "}", "}" ]
Get entity type by given instance of model @param $model @throws UnknownClassException @return string
[ "Get", "entity", "type", "by", "given", "instance", "of", "model" ]
678765232c8b9a45be9a08c17c13c1a4acfd3d20
https://github.com/artkost/yii2-qa/blob/678765232c8b9a45be9a08c17c13c1a4acfd3d20/models/Vote.php#L69-L79
37,693
artkost/yii2-qa
models/Vote.php
Vote.process
public static function process(ActiveRecord $model, $type) { $value = self::value($type); if (isset($model['votes'])) { $model['votes'] += $value; $vote = new self([ 'entity_id' => $model['id'], 'vote' => $value, 'entity' => self::modelEntityType($model) ]); if ($vote->save() && $model->save()) { return $model; } } return false; }
php
public static function process(ActiveRecord $model, $type) { $value = self::value($type); if (isset($model['votes'])) { $model['votes'] += $value; $vote = new self([ 'entity_id' => $model['id'], 'vote' => $value, 'entity' => self::modelEntityType($model) ]); if ($vote->save() && $model->save()) { return $model; } } return false; }
[ "public", "static", "function", "process", "(", "ActiveRecord", "$", "model", ",", "$", "type", ")", "{", "$", "value", "=", "self", "::", "value", "(", "$", "type", ")", ";", "if", "(", "isset", "(", "$", "model", "[", "'votes'", "]", ")", ")", "{", "$", "model", "[", "'votes'", "]", "+=", "$", "value", ";", "$", "vote", "=", "new", "self", "(", "[", "'entity_id'", "=>", "$", "model", "[", "'id'", "]", ",", "'vote'", "=>", "$", "value", ",", "'entity'", "=>", "self", "::", "modelEntityType", "(", "$", "model", ")", "]", ")", ";", "if", "(", "$", "vote", "->", "save", "(", ")", "&&", "$", "model", "->", "save", "(", ")", ")", "{", "return", "$", "model", ";", "}", "}", "return", "false", ";", "}" ]
Increment votes for given model @param ActiveRecord $model @param string $type of vote, up or down @return ActiveRecord
[ "Increment", "votes", "for", "given", "model" ]
678765232c8b9a45be9a08c17c13c1a4acfd3d20
https://github.com/artkost/yii2-qa/blob/678765232c8b9a45be9a08c17c13c1a4acfd3d20/models/Vote.php#L99-L118
37,694
artkost/yii2-qa
models/Tag.php
Tag.addTags
public static function addTags($tags) { self::updateAllCounters(['frequency' => 1], ['name' => $tags]); foreach ($tags as $name) { if (!self::find()->where(['name' => $name])->exists()) { (new self([ 'name' => $name, 'frequency' => 1 ]))->save(); } } }
php
public static function addTags($tags) { self::updateAllCounters(['frequency' => 1], ['name' => $tags]); foreach ($tags as $name) { if (!self::find()->where(['name' => $name])->exists()) { (new self([ 'name' => $name, 'frequency' => 1 ]))->save(); } } }
[ "public", "static", "function", "addTags", "(", "$", "tags", ")", "{", "self", "::", "updateAllCounters", "(", "[", "'frequency'", "=>", "1", "]", ",", "[", "'name'", "=>", "$", "tags", "]", ")", ";", "foreach", "(", "$", "tags", "as", "$", "name", ")", "{", "if", "(", "!", "self", "::", "find", "(", ")", "->", "where", "(", "[", "'name'", "=>", "$", "name", "]", ")", "->", "exists", "(", ")", ")", "{", "(", "new", "self", "(", "[", "'name'", "=>", "$", "name", ",", "'frequency'", "=>", "1", "]", ")", ")", "->", "save", "(", ")", ";", "}", "}", "}" ]
Update frequency of tags and add new tags @param $tags
[ "Update", "frequency", "of", "tags", "and", "add", "new", "tags" ]
678765232c8b9a45be9a08c17c13c1a4acfd3d20
https://github.com/artkost/yii2-qa/blob/678765232c8b9a45be9a08c17c13c1a4acfd3d20/models/Tag.php#L67-L79
37,695
artkost/yii2-qa
models/Tag.php
Tag.suggest
public static function suggest($keyword, $limit = 20) { /** @var self[] $tags */ $tags = self::find() ->where(['like', 'name', $keyword]) ->orderBy('frequency DESC, name') ->limit($limit) ->all(); $names = array(); foreach ($tags as $tag) { $names[] = ['word' => Html::encode($tag->name)]; } return $names; }
php
public static function suggest($keyword, $limit = 20) { /** @var self[] $tags */ $tags = self::find() ->where(['like', 'name', $keyword]) ->orderBy('frequency DESC, name') ->limit($limit) ->all(); $names = array(); foreach ($tags as $tag) { $names[] = ['word' => Html::encode($tag->name)]; } return $names; }
[ "public", "static", "function", "suggest", "(", "$", "keyword", ",", "$", "limit", "=", "20", ")", "{", "/** @var self[] $tags */", "$", "tags", "=", "self", "::", "find", "(", ")", "->", "where", "(", "[", "'like'", ",", "'name'", ",", "$", "keyword", "]", ")", "->", "orderBy", "(", "'frequency DESC, name'", ")", "->", "limit", "(", "$", "limit", ")", "->", "all", "(", ")", ";", "$", "names", "=", "array", "(", ")", ";", "foreach", "(", "$", "tags", "as", "$", "tag", ")", "{", "$", "names", "[", "]", "=", "[", "'word'", "=>", "Html", "::", "encode", "(", "$", "tag", "->", "name", ")", "]", ";", "}", "return", "$", "names", ";", "}" ]
Suggest tags by given keyword @param $keyword @param int $limit @return array
[ "Suggest", "tags", "by", "given", "keyword" ]
678765232c8b9a45be9a08c17c13c1a4acfd3d20
https://github.com/artkost/yii2-qa/blob/678765232c8b9a45be9a08c17c13c1a4acfd3d20/models/Tag.php#L101-L117
37,696
loduis/teamwork.com-project-management
src/Message/Reply.php
Reply.getByMessage
public function getByMessage($message_id, array $params = []) { $message_id = (int) $message_id; if ($message_id <= 0) { throw new Exception('Invalid param message_id'); } $validate = ['page', 'pagesize']; foreach ($params as $name=>$value) { if (!in_array(strtolower($name), $validate)) { unset($params[$name]); } } return $this->rest->get("messages/$message_id/replies", $params); }
php
public function getByMessage($message_id, array $params = []) { $message_id = (int) $message_id; if ($message_id <= 0) { throw new Exception('Invalid param message_id'); } $validate = ['page', 'pagesize']; foreach ($params as $name=>$value) { if (!in_array(strtolower($name), $validate)) { unset($params[$name]); } } return $this->rest->get("messages/$message_id/replies", $params); }
[ "public", "function", "getByMessage", "(", "$", "message_id", ",", "array", "$", "params", "=", "[", "]", ")", "{", "$", "message_id", "=", "(", "int", ")", "$", "message_id", ";", "if", "(", "$", "message_id", "<=", "0", ")", "{", "throw", "new", "Exception", "(", "'Invalid param message_id'", ")", ";", "}", "$", "validate", "=", "[", "'page'", ",", "'pagesize'", "]", ";", "foreach", "(", "$", "params", "as", "$", "name", "=>", "$", "value", ")", "{", "if", "(", "!", "in_array", "(", "strtolower", "(", "$", "name", ")", ",", "$", "validate", ")", ")", "{", "unset", "(", "$", "params", "[", "$", "name", "]", ")", ";", "}", "}", "return", "$", "this", "->", "rest", "->", "get", "(", "\"messages/$message_id/replies\"", ",", "$", "params", ")", ";", "}" ]
Retrieve Replies to a Message GET /messages/#{id}/replies.xml Uses the given messsage ID to retrieve a all replies to a message specified in the url. By default 20 records are returned at a time. You can pass "page" and "pageSize" to change this: eg. GET /messages/54/replies.xml?page=2&pageSize=50. The following headers are returned: "X-Records" - The total number of replies "X-Pages" - The total number of pages "X-Page" - The page you requested @param <type> $id @param array $params @return \TeamWorkPm\Response\Model @throws \TeamWorkPm\Exception
[ "Retrieve", "Replies", "to", "a", "Message" ]
29b2006dd450992cc7cc130d823b3a472dbad179
https://github.com/loduis/teamwork.com-project-management/blob/29b2006dd450992cc7cc130d823b3a472dbad179/src/Message/Reply.php#L44-L57
37,697
loduis/teamwork.com-project-management
src/Message.php
Message.getByProject
public function getByProject($project_id, $archive = false) { $project_id = (int) $project_id; if ($project_id <= 0) { throw new Exception('Invalid param project_id'); } $action = "projects/$project_id/$this->action"; if ($archive) { $action .= '/archive'; } return $this->rest->get($action); }
php
public function getByProject($project_id, $archive = false) { $project_id = (int) $project_id; if ($project_id <= 0) { throw new Exception('Invalid param project_id'); } $action = "projects/$project_id/$this->action"; if ($archive) { $action .= '/archive'; } return $this->rest->get($action); }
[ "public", "function", "getByProject", "(", "$", "project_id", ",", "$", "archive", "=", "false", ")", "{", "$", "project_id", "=", "(", "int", ")", "$", "project_id", ";", "if", "(", "$", "project_id", "<=", "0", ")", "{", "throw", "new", "Exception", "(", "'Invalid param project_id'", ")", ";", "}", "$", "action", "=", "\"projects/$project_id/$this->action\"", ";", "if", "(", "$", "archive", ")", "{", "$", "action", ".=", "'/archive'", ";", "}", "return", "$", "this", "->", "rest", "->", "get", "(", "$", "action", ")", ";", "}" ]
Retrieve Multiple Messages GET /projects/#{project_id}/posts.xml For the project ID supplied, will return the 25 most recent messages Get archived messages GET /projects/#{project_id}/posts/archive.xml Rather than the full message, this returns a summary record for each message in the specified project. @param $project_id @param bool $archive @return \TeamWorkPm\Response\Model @throws \TeamWorkPm\Exception
[ "Retrieve", "Multiple", "Messages" ]
29b2006dd450992cc7cc130d823b3a472dbad179
https://github.com/loduis/teamwork.com-project-management/blob/29b2006dd450992cc7cc130d823b3a472dbad179/src/Message.php#L54-L65
37,698
loduis/teamwork.com-project-management
src/Message.php
Message.getByProjectAndCategory
public function getByProjectAndCategory($project_id, $category_id, $archive = false) { $project_id = (int) $project_id; if ($project_id <= 0) { throw new \TeamWorkPm\Exception('Invalid param project_id'); } $category_id = (int) $category_id; if ($category_id <= 0) { throw new \TeamWorkPm\Exception('Invalid param category_id'); } $action = "projects/$project_id/cat/$category_id/$this->action"; if ($archive) { $action .= '/archive'; } return $this->rest->get($action); }
php
public function getByProjectAndCategory($project_id, $category_id, $archive = false) { $project_id = (int) $project_id; if ($project_id <= 0) { throw new \TeamWorkPm\Exception('Invalid param project_id'); } $category_id = (int) $category_id; if ($category_id <= 0) { throw new \TeamWorkPm\Exception('Invalid param category_id'); } $action = "projects/$project_id/cat/$category_id/$this->action"; if ($archive) { $action .= '/archive'; } return $this->rest->get($action); }
[ "public", "function", "getByProjectAndCategory", "(", "$", "project_id", ",", "$", "category_id", ",", "$", "archive", "=", "false", ")", "{", "$", "project_id", "=", "(", "int", ")", "$", "project_id", ";", "if", "(", "$", "project_id", "<=", "0", ")", "{", "throw", "new", "\\", "TeamWorkPm", "\\", "Exception", "(", "'Invalid param project_id'", ")", ";", "}", "$", "category_id", "=", "(", "int", ")", "$", "category_id", ";", "if", "(", "$", "category_id", "<=", "0", ")", "{", "throw", "new", "\\", "TeamWorkPm", "\\", "Exception", "(", "'Invalid param category_id'", ")", ";", "}", "$", "action", "=", "\"projects/$project_id/cat/$category_id/$this->action\"", ";", "if", "(", "$", "archive", ")", "{", "$", "action", ".=", "'/archive'", ";", "}", "return", "$", "this", "->", "rest", "->", "get", "(", "$", "action", ")", ";", "}" ]
Retrieve Messages by Category GET /projects/#{project_id}/cat/#{category_id}/posts.xml As before, will return you the most recent 25 messages, this time limited by project and category. Get archived messages by category GET /projects/#{project_id}/cat/#{category_id}/posts/archive.xml As above, but returns only the posts in the given category @param int $project_id @param int $category_id @param bool $archive @return \TeamWorkPm\Response\Model @throws \TeamWorkPm\Exception
[ "Retrieve", "Messages", "by", "Category" ]
29b2006dd450992cc7cc130d823b3a472dbad179
https://github.com/loduis/teamwork.com-project-management/blob/29b2006dd450992cc7cc130d823b3a472dbad179/src/Message.php#L87-L102
37,699
loduis/teamwork.com-project-management
src/Message.php
Message.insert
public function insert(array $data) { $project_id = empty($data['project_id']) ? 0: (int) $data['project_id']; if ($project_id <= 0) { throw new \TeamWorkPm\Exception('Required field project_id'); } if (!empty($data['files'])) { $file = \TeamWorkPm\Factory::build('file'); $data['pending_file_attachments'] = $file->upload($data['files']); unset($data['files']); } return $this->rest->post("projects/$project_id/$this->action", $data); }
php
public function insert(array $data) { $project_id = empty($data['project_id']) ? 0: (int) $data['project_id']; if ($project_id <= 0) { throw new \TeamWorkPm\Exception('Required field project_id'); } if (!empty($data['files'])) { $file = \TeamWorkPm\Factory::build('file'); $data['pending_file_attachments'] = $file->upload($data['files']); unset($data['files']); } return $this->rest->post("projects/$project_id/$this->action", $data); }
[ "public", "function", "insert", "(", "array", "$", "data", ")", "{", "$", "project_id", "=", "empty", "(", "$", "data", "[", "'project_id'", "]", ")", "?", "0", ":", "(", "int", ")", "$", "data", "[", "'project_id'", "]", ";", "if", "(", "$", "project_id", "<=", "0", ")", "{", "throw", "new", "\\", "TeamWorkPm", "\\", "Exception", "(", "'Required field project_id'", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "data", "[", "'files'", "]", ")", ")", "{", "$", "file", "=", "\\", "TeamWorkPm", "\\", "Factory", "::", "build", "(", "'file'", ")", ";", "$", "data", "[", "'pending_file_attachments'", "]", "=", "$", "file", "->", "upload", "(", "$", "data", "[", "'files'", "]", ")", ";", "unset", "(", "$", "data", "[", "'files'", "]", ")", ";", "}", "return", "$", "this", "->", "rest", "->", "post", "(", "\"projects/$project_id/$this->action\"", ",", "$", "data", ")", ";", "}" ]
Create a message POST /projects/#{project_id}/posts.xml This will create a new message. Also, you have the option of sending a notification to a list of people you specify. @param array $data @return int @throws \TeamWorkPm\Exception
[ "Create", "a", "message" ]
29b2006dd450992cc7cc130d823b3a472dbad179
https://github.com/loduis/teamwork.com-project-management/blob/29b2006dd450992cc7cc130d823b3a472dbad179/src/Message.php#L117-L129