repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
xiewulong/yii2-wechat
Manager.php
Manager.getMaterials
public function getMaterials($type, $all = true, $page = 1, $count = 20) { $offset = ($page - 1) * $count; $data = $this->getData('/cgi-bin/material/batchget_material', [ 'access_token' => $this->getAccessToken(), ], Json::encode([ 'type' => $type, 'offset' => $offset, 'count' => $count, ])); if($this->errcode == 0) { if($all && $offset + $data['item_count'] < $data['total_count']) { if($_data = $this->getMaterials($type, $all, $page + 1, $count)) { $data['item_count'] += $_data['item_count']; $data['item'] = array_merge($data['item'], $_data['item']); } } return $data; } return []; }
php
public function getMaterials($type, $all = true, $page = 1, $count = 20) { $offset = ($page - 1) * $count; $data = $this->getData('/cgi-bin/material/batchget_material', [ 'access_token' => $this->getAccessToken(), ], Json::encode([ 'type' => $type, 'offset' => $offset, 'count' => $count, ])); if($this->errcode == 0) { if($all && $offset + $data['item_count'] < $data['total_count']) { if($_data = $this->getMaterials($type, $all, $page + 1, $count)) { $data['item_count'] += $_data['item_count']; $data['item'] = array_merge($data['item'], $_data['item']); } } return $data; } return []; }
获取素材列表 @since 0.0.1 @param {string} $type 素材的类型 @param {boolean} [$all=true] 是否返回所有 @param {integer} [$page=1] 页码 @param {integer} [$count=20] 每页数量 @return {array} @example \Yii::$app->wechat->getMaterials($type, $all, $page, $count);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L408-L430
xiewulong/yii2-wechat
Manager.php
Manager.deleteMaterial
public function deleteMaterial($media_id) { $data = $this->getData('/cgi-bin/material/del_material', [ 'access_token' => $this->getAccessToken(), ], Json::encode(['media_id' => $media_id])); return $this->errcode == 0; }
php
public function deleteMaterial($media_id) { $data = $this->getData('/cgi-bin/material/del_material', [ 'access_token' => $this->getAccessToken(), ], Json::encode(['media_id' => $media_id])); return $this->errcode == 0; }
删除永久素材 @since 0.0.1 @param {string} $media_id 媒体文件ID @return {boolean} @example \Yii::$app->wechat->deleteMaterial($media_id);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L440-L446
xiewulong/yii2-wechat
Manager.php
Manager.getMaterial
public function getMaterial($media_id) { $data = $this->getData('/cgi-bin/material/get_material', [ 'access_token' => $this->getAccessToken(), ], Json::encode(['media_id' => $media_id])); return $this->errcode == 0 ? (isset($data['content']) && isset($data['extension']) ? $this->saveFile($data) : $data) : null; }
php
public function getMaterial($media_id) { $data = $this->getData('/cgi-bin/material/get_material', [ 'access_token' => $this->getAccessToken(), ], Json::encode(['media_id' => $media_id])); return $this->errcode == 0 ? (isset($data['content']) && isset($data['extension']) ? $this->saveFile($data) : $data) : null; }
获取永久素材 @since 0.0.1 @param {string} $media_id 媒体文件ID @return {string|array|null} @example \Yii::$app->wechat->getMaterial($media_id);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L456-L462
xiewulong/yii2-wechat
Manager.php
Manager.addMaterial
public function addMaterial($material_id) { $material = WechatMaterial::findOne($material_id); if(!$material) { throw new ErrorException('数据查询失败'); }else if($materialMedia = WechatMaterialMedia::findOne(['appid' => $this->app->appid, 'material_id' => $material->id, 'expired_at' => 0])) { return $materialMedia->id; } $postData = ['media' => '@' . $material->localFile]; if($material->type == 'video') { if($material->title == '') { throw new ErrorException('视频标题不能为空'); } $postData['description'] = Json::encode([ 'title' => $material->title, 'introduction' => $material->description, ]); } $data = $this->getData('/cgi-bin/material/add_material', [ 'access_token' => $this->getAccessToken(), 'type' => $material->type, ], $postData); $material->cleanTmp(); if($this->errcode == 0) { $materialMedia = new WechatMaterialMedia; $materialMedia->appid = $this->app->appid; $materialMedia->material_id = $material->id; $materialMedia->media_id = $data['media_id']; if(isset($data['url'])) { $materialMedia->url = $data['url']; } if($materialMedia->save()) { return $materialMedia->id; } } return 0; }
php
public function addMaterial($material_id) { $material = WechatMaterial::findOne($material_id); if(!$material) { throw new ErrorException('数据查询失败'); }else if($materialMedia = WechatMaterialMedia::findOne(['appid' => $this->app->appid, 'material_id' => $material->id, 'expired_at' => 0])) { return $materialMedia->id; } $postData = ['media' => '@' . $material->localFile]; if($material->type == 'video') { if($material->title == '') { throw new ErrorException('视频标题不能为空'); } $postData['description'] = Json::encode([ 'title' => $material->title, 'introduction' => $material->description, ]); } $data = $this->getData('/cgi-bin/material/add_material', [ 'access_token' => $this->getAccessToken(), 'type' => $material->type, ], $postData); $material->cleanTmp(); if($this->errcode == 0) { $materialMedia = new WechatMaterialMedia; $materialMedia->appid = $this->app->appid; $materialMedia->material_id = $material->id; $materialMedia->media_id = $data['media_id']; if(isset($data['url'])) { $materialMedia->url = $data['url']; } if($materialMedia->save()) { return $materialMedia->id; } } return 0; }
新增永久素材 @since 0.0.1 @param {integer} $material_id 素材id @return {integer} @example \Yii::$app->wechat->addMaterial($material_id);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L472-L511
xiewulong/yii2-wechat
Manager.php
Manager.getMedia
public function getMedia($media_id) { $data = $this->getData('/cgi-bin/media/get', [ 'access_token' => $this->getAccessToken(), 'media_id' => $media_id, ]); return $this->errcode == 0 ? $this->saveFile($data) : null; }
php
public function getMedia($media_id) { $data = $this->getData('/cgi-bin/media/get', [ 'access_token' => $this->getAccessToken(), 'media_id' => $media_id, ]); return $this->errcode == 0 ? $this->saveFile($data) : null; }
获取临时素材 @since 0.0.1 @param {string} $media_id 媒体文件ID @return {string|null} @example \Yii::$app->wechat->getMedia($media_id);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L521-L528
xiewulong/yii2-wechat
Manager.php
Manager.addMedia
public function addMedia($material_id) { $material = WechatMaterial::findOne($material_id); if(!$material) { throw new ErrorException('数据查询失败'); } $data = $this->getData('/cgi-bin/media/upload', [ 'access_token' => $this->getAccessToken(), 'type' => $material->type, ], ['media' => '@' . $material->localFile]); $material->cleanTmp(); if($this->errcode == 0) { $materialMedia = new WechatMaterialMedia; $materialMedia->appid = $this->app->appid; $materialMedia->material_id = $material->id; $materialMedia->media_id = $data['media_id']; $materialMedia->expired_at = $data['created_at'] + $this->effectiveTimeOfTemporaryMaterial; if($materialMedia->save()) { return $materialMedia->id; } } return 0; }
php
public function addMedia($material_id) { $material = WechatMaterial::findOne($material_id); if(!$material) { throw new ErrorException('数据查询失败'); } $data = $this->getData('/cgi-bin/media/upload', [ 'access_token' => $this->getAccessToken(), 'type' => $material->type, ], ['media' => '@' . $material->localFile]); $material->cleanTmp(); if($this->errcode == 0) { $materialMedia = new WechatMaterialMedia; $materialMedia->appid = $this->app->appid; $materialMedia->material_id = $material->id; $materialMedia->media_id = $data['media_id']; $materialMedia->expired_at = $data['created_at'] + $this->effectiveTimeOfTemporaryMaterial; if($materialMedia->save()) { return $materialMedia->id; } } return 0; }
新增临时素材 @since 0.0.1 @param {integer} $material_id 素材id @return {integer} @example \Yii::$app->wechat->addMedia($material_id);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L538-L562
xiewulong/yii2-wechat
Manager.php
Manager.tryMatchMenu
public function tryMatchMenu($openid) { $data = $this->getData('/cgi-bin/menu/trymatch', [ 'access_token' => $this->getAccessToken(), ], Json::encode(['user_id' => $openid])); return $this->errcode == 0 ? $data : []; }
php
public function tryMatchMenu($openid) { $data = $this->getData('/cgi-bin/menu/trymatch', [ 'access_token' => $this->getAccessToken(), ], Json::encode(['user_id' => $openid])); return $this->errcode == 0 ? $data : []; }
测试个性化菜单匹配结果 @since 0.0.1 @param {string} $openid OpenID或微信号 @return {array} @example \Yii::$app->wechat->tryMatchMenu($openid);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L587-L593
xiewulong/yii2-wechat
Manager.php
Manager.deleteConditionalMenu
public function deleteConditionalMenu($menuid) { $data = $this->getData('/cgi-bin/menu/delconditional', [ 'access_token' => $this->getAccessToken(), ], Json::encode(['menuid' => $menuid])); return $this->errcode == 0 && WechatMenu::deleteAll(['appid' => $this->app->appid, 'conditional' => 1, 'menuid' => $menuid]); }
php
public function deleteConditionalMenu($menuid) { $data = $this->getData('/cgi-bin/menu/delconditional', [ 'access_token' => $this->getAccessToken(), ], Json::encode(['menuid' => $menuid])); return $this->errcode == 0 && WechatMenu::deleteAll(['appid' => $this->app->appid, 'conditional' => 1, 'menuid' => $menuid]); }
删除个性化菜单 @since 0.0.1 @param {integer} $menuid 菜单id @return {boolean} @example \Yii::$app->wechat->deleteConditionalMenu($menuid);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L603-L609
xiewulong/yii2-wechat
Manager.php
Manager.deleteMenu
public function deleteMenu() { $data = $this->getData('/cgi-bin/menu/delete', [ 'access_token' => $this->getAccessToken(), ]); return $this->errcode == 0 && WechatMenu::deleteAll(['appid' => $this->app->appid]); }
php
public function deleteMenu() { $data = $this->getData('/cgi-bin/menu/delete', [ 'access_token' => $this->getAccessToken(), ]); return $this->errcode == 0 && WechatMenu::deleteAll(['appid' => $this->app->appid]); }
删除自定义(个性化)菜单 @since 0.0.1 @return {boolean} @example \Yii::$app->wechat->deleteMenu();
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L618-L624
xiewulong/yii2-wechat
Manager.php
Manager.updateMenu
public function updateMenu() { $data = $this->getData('/cgi-bin/menu/create', [ 'access_token' => $this->getAccessToken(), ], Json::encode(['button' => WechatMenu::getMenu($this->app->appid)])); return $this->errcode == 0; }
php
public function updateMenu() { $data = $this->getData('/cgi-bin/menu/create', [ 'access_token' => $this->getAccessToken(), ], Json::encode(['button' => WechatMenu::getMenu($this->app->appid)])); return $this->errcode == 0; }
更新自定义菜单 @method updateMenu @since 0.0.1 @return {boolean} @example \Yii::$app->wechat->updateMenu();
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L633-L639
xiewulong/yii2-wechat
Manager.php
Manager.createMenu
public function createMenu($button, $matchrule = null) { $postData = ['button' => $button]; if($matchrule) { $postData['matchrule'] = $matchrule; } $data = $this->getData('/cgi-bin/menu/' . ($matchrule ? 'addconditional' : 'create'), [ 'access_token' => $this->getAccessToken(), ], Json::encode($postData)); if(isset($data['menuid'])) { $postData['menuid'] = $data['menuid']; } return $this->errcode == 0 && WechatMenu::createMenu($this->app->appid, $postData); }
php
public function createMenu($button, $matchrule = null) { $postData = ['button' => $button]; if($matchrule) { $postData['matchrule'] = $matchrule; } $data = $this->getData('/cgi-bin/menu/' . ($matchrule ? 'addconditional' : 'create'), [ 'access_token' => $this->getAccessToken(), ], Json::encode($postData)); if(isset($data['menuid'])) { $postData['menuid'] = $data['menuid']; } return $this->errcode == 0 && WechatMenu::createMenu($this->app->appid, $postData); }
创建自定义(个性化)菜单 @since 0.0.1 @param {array} $button 菜单数据 @param {array} [$matchrule] 个性化菜单匹配规则 @return {boolean} @example \Yii::$app->wechat->createMenu($button, $matchrule);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L650-L665
xiewulong/yii2-wechat
Manager.php
Manager.refreshMenu
public function refreshMenu() { $data = $this->getMenu(); if($data && isset($data['menu']) && isset($data['menu']['button'])) { WechatMenu::deleteAll(['appid' => $this->app->appid]); WechatMenu::addMenu($this->app->appid, $data['menu']['button'], isset($data['menu']['menuid']) ? $data['menu']['menuid'] : null); if(isset($data['conditionalmenu'])) { foreach($data['conditionalmenu'] as $conditionalmenu) { WechatMenu::addMenu($this->app->appid, $conditionalmenu['button'], $conditionalmenu['menuid'], $conditionalmenu['matchrule']); } } return true; } return false; }
php
public function refreshMenu() { $data = $this->getMenu(); if($data && isset($data['menu']) && isset($data['menu']['button'])) { WechatMenu::deleteAll(['appid' => $this->app->appid]); WechatMenu::addMenu($this->app->appid, $data['menu']['button'], isset($data['menu']['menuid']) ? $data['menu']['menuid'] : null); if(isset($data['conditionalmenu'])) { foreach($data['conditionalmenu'] as $conditionalmenu) { WechatMenu::addMenu($this->app->appid, $conditionalmenu['button'], $conditionalmenu['menuid'], $conditionalmenu['matchrule']); } } return true; } return false; }
刷新自定义(个性化)菜单 @since 0.0.1 @return {boolean} @example \Yii::$app->wechat->refreshMenu();
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L674-L689
xiewulong/yii2-wechat
Manager.php
Manager.updateGroupUsers
public function updateGroupUsers($uids, $gid) { if(is_array($uids)) { $uids = implode(',', $uids); } $query = WechatUser::find()->where("id in ($uids) and groupid <> $gid"); $users = $query->all(); $openids = ArrayHelper::getColumn($users, 'openid'); if(!$openids) { return true; } $data = $this->getData('/cgi-bin/groups/members/batchupdate', [ 'access_token' => $this->getAccessToken(), ], Json::encode([ 'openid_list' => $openids, 'to_groupid' => $gid, ])); $result = $this->errcode == 0; if($result) { foreach($users as $user) { if($user->group->updateCounters(['count' => -1])) { $user->groupid = $gid; if($user->save()) { $user->refresh(); $user->group->updateCounters(['count' => 1]); } } } } return $result; }
php
public function updateGroupUsers($uids, $gid) { if(is_array($uids)) { $uids = implode(',', $uids); } $query = WechatUser::find()->where("id in ($uids) and groupid <> $gid"); $users = $query->all(); $openids = ArrayHelper::getColumn($users, 'openid'); if(!$openids) { return true; } $data = $this->getData('/cgi-bin/groups/members/batchupdate', [ 'access_token' => $this->getAccessToken(), ], Json::encode([ 'openid_list' => $openids, 'to_groupid' => $gid, ])); $result = $this->errcode == 0; if($result) { foreach($users as $user) { if($user->group->updateCounters(['count' => -1])) { $user->groupid = $gid; if($user->save()) { $user->refresh(); $user->group->updateCounters(['count' => 1]); } } } } return $result; }
批量移动用户分组 @since 0.0.1 @param {string|array} $uids 用户id @param {integer} $gid 用户分组gid @return {boolean} @example \Yii::$app->wechat->updateGroupUsers($uids, $gid);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L715-L749
xiewulong/yii2-wechat
Manager.php
Manager.updateGroupUser
public function updateGroupUser($uid, $gid) { $user = WechatUser::findOne($uid); if(!$user) { throw new ErrorException('数据查询失败'); } if($user->groupid == $gid) { return true; } $data = $this->getData('/cgi-bin/groups/members/update', [ 'access_token' => $this->getAccessToken(), ], Json::encode([ 'openid' => $user->openid, 'to_groupid' => $gid, ])); $result = $this->errcode == 0; if($result && $user->group->updateCounters(['count' => -1])) { $user->groupid = $gid; if($user->save()) { $user->refresh(); return $user->group->updateCounters(['count' => 1]); } } return $result; }
php
public function updateGroupUser($uid, $gid) { $user = WechatUser::findOne($uid); if(!$user) { throw new ErrorException('数据查询失败'); } if($user->groupid == $gid) { return true; } $data = $this->getData('/cgi-bin/groups/members/update', [ 'access_token' => $this->getAccessToken(), ], Json::encode([ 'openid' => $user->openid, 'to_groupid' => $gid, ])); $result = $this->errcode == 0; if($result && $user->group->updateCounters(['count' => -1])) { $user->groupid = $gid; if($user->save()) { $user->refresh(); return $user->group->updateCounters(['count' => 1]); } } return $result; }
移动用户分组 @since 0.0.1 @param {integer} $uid 用户id @param {integer} $gid 用户分组gid @return {boolean} @example \Yii::$app->wechat->updateGroupUser($uid, $gid);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L760-L787
xiewulong/yii2-wechat
Manager.php
Manager.deleteGroup
public function deleteGroup($gid) { $group = WechatUserGroup::findOne($gid); if(!$group) { throw new ErrorException('数据查询失败'); } $data = $this->getData('/cgi-bin/groups/delete', [ 'access_token' => $this->getAccessToken(), ], Json::encode([ 'group' => ['id' => $group->gid], ])); if(empty($data)) { return $group->delete(); } return false; }
php
public function deleteGroup($gid) { $group = WechatUserGroup::findOne($gid); if(!$group) { throw new ErrorException('数据查询失败'); } $data = $this->getData('/cgi-bin/groups/delete', [ 'access_token' => $this->getAccessToken(), ], Json::encode([ 'group' => ['id' => $group->gid], ])); if(empty($data)) { return $group->delete(); } return false; }
删除用户分组 @since 0.0.1 @param {integer} $gid 用户分组id @param {string} [$name] 用户分组名字, 30个字符以内, 默认直接取数据库中的值 @return {boolean} @example \Yii::$app->wechat->deleteGroup($gid, $name);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L798-L815
xiewulong/yii2-wechat
Manager.php
Manager.updateGroup
public function updateGroup($gid, $name = null) { $group = WechatUserGroup::findOne($gid); if(!$group) { throw new ErrorException('数据查询失败'); } $data = $this->getData('/cgi-bin/groups/update', [ 'access_token' => $this->getAccessToken(), ], Json::encode([ 'group' => ['id' => $group->gid, 'name' => $name ? : $group->name], ])); $result = $this->errcode == 0; if($result && $name) { $group->name = $name; $group->save(); } return $result; }
php
public function updateGroup($gid, $name = null) { $group = WechatUserGroup::findOne($gid); if(!$group) { throw new ErrorException('数据查询失败'); } $data = $this->getData('/cgi-bin/groups/update', [ 'access_token' => $this->getAccessToken(), ], Json::encode([ 'group' => ['id' => $group->gid, 'name' => $name ? : $group->name], ])); $result = $this->errcode == 0; if($result && $name) { $group->name = $name; $group->save(); } return $result; }
修改用户分组名 @since 0.0.1 @param {integer} $gid 用户分组id @param {string} [$name] 分组名字, 30个字符以内, 默认直接取数据库中的值 @return {boolean} @example \Yii::$app->wechat->updateGroup($gid, $name);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L826-L845
xiewulong/yii2-wechat
Manager.php
Manager.createGroup
public function createGroup($name) { $data = $this->getData('/cgi-bin/groups/create', [ 'access_token' => $this->getAccessToken(), ], Json::encode([ 'group' => ['name' => $name], ])); if(isset($data['group'])) { $group = new WechatUserGroup; $group->appid = $this->app->appid; $group->gid = $data['group']['id']; $group->name = $data['group']['name']; if($group->save()) { return $group->id; } } return 0; }
php
public function createGroup($name) { $data = $this->getData('/cgi-bin/groups/create', [ 'access_token' => $this->getAccessToken(), ], Json::encode([ 'group' => ['name' => $name], ])); if(isset($data['group'])) { $group = new WechatUserGroup; $group->appid = $this->app->appid; $group->gid = $data['group']['id']; $group->name = $data['group']['name']; if($group->save()) { return $group->id; } } return 0; }
创建用户分组 @since 0.0.1 @param {string} $name 用户分组名字, 30个字符以内 @return {object} @example \Yii::$app->wechat->createGroup($name);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L855-L873
xiewulong/yii2-wechat
Manager.php
Manager.getGroups
public function getGroups() { $data = $this->getData('/cgi-bin/groups/get', [ 'access_token' => $this->getAccessToken(), ]); if(isset($data['groups'])) { foreach($data['groups'] as $_group) { $group = WechatUserGroup::findOne(['appid' => $this->app->appid, 'gid' => $_group['id']]); if(!$group) { $group = new WechatUserGroup; $group->appid = $this->app->appid; $group->gid = $_group['id']; } $group->name = $_group['name']; $group->count = $_group['count']; $group->save(); } } return $this->errcode == 0; }
php
public function getGroups() { $data = $this->getData('/cgi-bin/groups/get', [ 'access_token' => $this->getAccessToken(), ]); if(isset($data['groups'])) { foreach($data['groups'] as $_group) { $group = WechatUserGroup::findOne(['appid' => $this->app->appid, 'gid' => $_group['id']]); if(!$group) { $group = new WechatUserGroup; $group->appid = $this->app->appid; $group->gid = $_group['id']; } $group->name = $_group['name']; $group->count = $_group['count']; $group->save(); } } return $this->errcode == 0; }
查询所有用户分组 @since 0.0.1 @return {boolean} @example \Yii::$app->wechat->getGroups();
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L882-L902
xiewulong/yii2-wechat
Manager.php
Manager.getUserGroup
public function getUserGroup($openid) { $data = $this->getData('/cgi-bin/groups/getid', [ 'access_token' => $this->getAccessToken(), ], Json::encode([ 'openid' => $openid, ])); return isset($data['groupid']) ? $data['groupid'] : -1; }
php
public function getUserGroup($openid) { $data = $this->getData('/cgi-bin/groups/getid', [ 'access_token' => $this->getAccessToken(), ], Json::encode([ 'openid' => $openid, ])); return isset($data['groupid']) ? $data['groupid'] : -1; }
查询用户所在分组 @since 0.0.1 @param {string} $openid OpenID @return {integer} @example \Yii::$app->wechat->getUserGroup($openid);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L912-L920
xiewulong/yii2-wechat
Manager.php
Manager.updateUserRemark
public function updateUserRemark($uid, $remark = null) { $user = WechatUser::findOne($uid); if(!$user) { throw new ErrorException('数据查询失败'); } $data = $this->getData('/cgi-bin/user/info/updateremark', [ 'access_token' => $this->getAccessToken(), ], Json::encode([ 'openid' => $user->openid, 'remark' => $remark ? : $user->remark, ])); $result = $this->errcode == 0; if($result && $remark) { $user->remark = $remark; $user->save(); } return $result; }
php
public function updateUserRemark($uid, $remark = null) { $user = WechatUser::findOne($uid); if(!$user) { throw new ErrorException('数据查询失败'); } $data = $this->getData('/cgi-bin/user/info/updateremark', [ 'access_token' => $this->getAccessToken(), ], Json::encode([ 'openid' => $user->openid, 'remark' => $remark ? : $user->remark, ])); $result = $this->errcode == 0; if($result && $remark) { $user->remark = $remark; $user->save(); } return $result; }
设置用户备注名 @since 0.0.1 @param {integer} $uid 用户id @param {string} [$remark] 备注名, 长度必须小于30字符, 默认直接取数据库中的值 @return {boolean} @example \Yii::$app->wechat->updateUserRemark($uid, $remark);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L931-L951
xiewulong/yii2-wechat
Manager.php
Manager.refreshUser
public function refreshUser($uid) { $user = WechatUser::findOne($uid); if(!$user) { throw new ErrorException('数据查询失败'); } $data = $this->getData('/cgi-bin/user/info', [ 'access_token' => $this->getAccessToken(), 'openid' => $user->openid, 'lang' => \Yii::$app->language, ]); $result = $this->errcode == 0; if($result) { $user->subscribe = $data['subscribe']; if($user->subscribe == 1) { $user->subscribed_at = $data['subscribe_time']; $user->name = $data['nickname']; $user->sex = $data['sex']; $user->country = $data['country']; $user->city = $data['city']; $user->province = $data['province']; $user->language = $data['language']; $user->headimgurl = $data['headimgurl']; $user->remark = $data['remark']; $user->groupid = $data['groupid']; } if(isset($data['unionid'])) { $user->unionid = $data['unionid']; } $user->save(); } return $result; }
php
public function refreshUser($uid) { $user = WechatUser::findOne($uid); if(!$user) { throw new ErrorException('数据查询失败'); } $data = $this->getData('/cgi-bin/user/info', [ 'access_token' => $this->getAccessToken(), 'openid' => $user->openid, 'lang' => \Yii::$app->language, ]); $result = $this->errcode == 0; if($result) { $user->subscribe = $data['subscribe']; if($user->subscribe == 1) { $user->subscribed_at = $data['subscribe_time']; $user->name = $data['nickname']; $user->sex = $data['sex']; $user->country = $data['country']; $user->city = $data['city']; $user->province = $data['province']; $user->language = $data['language']; $user->headimgurl = $data['headimgurl']; $user->remark = $data['remark']; $user->groupid = $data['groupid']; } if(isset($data['unionid'])) { $user->unionid = $data['unionid']; } $user->save(); } return $result; }
刷新用户基本信息 @since 0.0.1 @param {integer} $uid 用户id @return {boolean} @example \Yii::$app->wechat->refreshUser($uid);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L961-L995
xiewulong/yii2-wechat
Manager.php
Manager.refreshUsers
public function refreshUsers($page = 1) { $query = WechatUser::find()->where(['appid' => $this->app->appid])->select('openid'); $pageSize = 100; $pagination = new Pagination([ 'totalCount' => $query->count(), 'defaultPageSize' => $pageSize, 'pageSizeLimit' => [0, $pageSize], ]); $pagination->setPage($page - 1, true); $users = $query->offset($pagination->offset) ->limit($pagination->limit) ->asArray() ->all(); $user_list = []; foreach($users as $user) { $user['lang'] = \Yii::$app->language; $user_list['user_list'][] = $user; } if($user_list) { $data = $this->getData('/cgi-bin/user/info/batchget', [ 'access_token' => $this->getAccessToken(), ], Json::encode($user_list)); if(isset($data['user_info_list'])) { foreach($data['user_info_list'] as $_user) { $user = WechatUser::findOne(['appid' => $this->app->appid, 'openid' => $_user['openid']]); if(!$user) { $user = new WechatUser; $user->appid = $this->app->appid; $user->openid = $_user['openid']; } $user->subscribe = $_user['subscribe']; if($user->subscribe == 1) { $user->subscribed_at = $_user['subscribed_at']; $user->name = $_user['nickname']; $user->sex = $_user['sex']; $user->country = $_user['country']; $user->city = $_user['city']; $user->province = $_user['province']; $user->language = $_user['language']; $user->headimgurl = $_user['headimgurl']; $user->remark = $_user['remark']; $user->groupid = $_user['groupid']; } if(isset($_user['unionid'])) { $user->unionid = $_user['unionid']; } $user->save(); } } } return $page < $pagination->pageCount ? $this->refreshUsers($page + 1) : $this->errcode == 0; }
php
public function refreshUsers($page = 1) { $query = WechatUser::find()->where(['appid' => $this->app->appid])->select('openid'); $pageSize = 100; $pagination = new Pagination([ 'totalCount' => $query->count(), 'defaultPageSize' => $pageSize, 'pageSizeLimit' => [0, $pageSize], ]); $pagination->setPage($page - 1, true); $users = $query->offset($pagination->offset) ->limit($pagination->limit) ->asArray() ->all(); $user_list = []; foreach($users as $user) { $user['lang'] = \Yii::$app->language; $user_list['user_list'][] = $user; } if($user_list) { $data = $this->getData('/cgi-bin/user/info/batchget', [ 'access_token' => $this->getAccessToken(), ], Json::encode($user_list)); if(isset($data['user_info_list'])) { foreach($data['user_info_list'] as $_user) { $user = WechatUser::findOne(['appid' => $this->app->appid, 'openid' => $_user['openid']]); if(!$user) { $user = new WechatUser; $user->appid = $this->app->appid; $user->openid = $_user['openid']; } $user->subscribe = $_user['subscribe']; if($user->subscribe == 1) { $user->subscribed_at = $_user['subscribed_at']; $user->name = $_user['nickname']; $user->sex = $_user['sex']; $user->country = $_user['country']; $user->city = $_user['city']; $user->province = $_user['province']; $user->language = $_user['language']; $user->headimgurl = $_user['headimgurl']; $user->remark = $_user['remark']; $user->groupid = $_user['groupid']; } if(isset($_user['unionid'])) { $user->unionid = $_user['unionid']; } $user->save(); } } } return $page < $pagination->pageCount ? $this->refreshUsers($page + 1) : $this->errcode == 0; }
刷新所有用户基本信息 @since 0.0.1 @param {integer} [$page=1] 页码 @return {boolean} @example \Yii::$app->wechat->refreshUsers($page);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L1005-L1061
xiewulong/yii2-wechat
Manager.php
Manager.getUsers
public function getUsers($next_openid = null) { $data = $this->getData('/cgi-bin/user/get', [ 'access_token' => $this->getAccessToken(), 'next_openid' => $next_openid, ]); if(isset($data['count']) && $data['count'] && isset($data['data']) && isset($data['data']['openid'])) { foreach($data['data']['openid'] as $openid) { if($user = WechatUser::findOne(['appid' => $this->app->appid, 'openid' => $openid])) { if($user->subscribe == 0) { $user->subscribe = 1; $user->save(); } } else { $user = new WechatUser; $user->appid = $this->app->appid; $user->openid = $openid; $user->subscribe = 1; $user->save(); } } } return isset($data['next_openid']) && $data['next_openid'] ? $this->getUsers($data['next_openid']) : $this->errcode == 0; }
php
public function getUsers($next_openid = null) { $data = $this->getData('/cgi-bin/user/get', [ 'access_token' => $this->getAccessToken(), 'next_openid' => $next_openid, ]); if(isset($data['count']) && $data['count'] && isset($data['data']) && isset($data['data']['openid'])) { foreach($data['data']['openid'] as $openid) { if($user = WechatUser::findOne(['appid' => $this->app->appid, 'openid' => $openid])) { if($user->subscribe == 0) { $user->subscribe = 1; $user->save(); } } else { $user = new WechatUser; $user->appid = $this->app->appid; $user->openid = $openid; $user->subscribe = 1; $user->save(); } } } return isset($data['next_openid']) && $data['next_openid'] ? $this->getUsers($data['next_openid']) : $this->errcode == 0; }
获取用户列表 @since 0.0.1 @param {string} [$next_openid] 第一个拉取的OPENID, 不填默认从头开始拉取 @return {boolean} @example \Yii::$app->wechat->getUsers($next_openid);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L1071-L1095
xiewulong/yii2-wechat
Manager.php
Manager.getCallbackIp
public function getCallbackIp() { if(empty($this->app->ip_list)) { $this->refreshIpList(); } return $this->app->ipListArray; }
php
public function getCallbackIp() { if(empty($this->app->ip_list)) { $this->refreshIpList(); } return $this->app->ipListArray; }
获取微信服务器IP地址 @since 0.0.1 @return {array} @example \Yii::$app->wechat->getCallbackIp();
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L1104-L1110
xiewulong/yii2-wechat
Manager.php
Manager.refreshIpList
public function refreshIpList() { $data = $this->getData('/cgi-bin/getcallbackip', [ 'access_token' => $this->getAccessToken(), ]); if(isset($data['ip_list'])) { $this->app->ip_list = Json::encode($data['ip_list']); return $this->app->save(); } return $this->errcode == 0; }
php
public function refreshIpList() { $data = $this->getData('/cgi-bin/getcallbackip', [ 'access_token' => $this->getAccessToken(), ]); if(isset($data['ip_list'])) { $this->app->ip_list = Json::encode($data['ip_list']); return $this->app->save(); } return $this->errcode == 0; }
刷新微信服务器IP地址 @since 0.0.1 @return {boolean} @example \Yii::$app->wechat->refreshIpList();
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L1119-L1130
xiewulong/yii2-wechat
Manager.php
Manager.getJsapiConfig
public function getJsapiConfig($url = null) { $params = [ 'jsapi_ticket' => $this->getJsapiTicket(), 'noncestr' => md5(mt_rand()), 'timestamp' => strval(time()), 'url' => $url ? : \Yii::$app->request->absoluteUrl, ]; return [ 'appId' => $this->app->appid, 'timestamp' => $params['timestamp'], 'nonceStr' => $params['noncestr'], 'signature' => $this->sign($params), 'signType' => 'sha1', ]; }
php
public function getJsapiConfig($url = null) { $params = [ 'jsapi_ticket' => $this->getJsapiTicket(), 'noncestr' => md5(mt_rand()), 'timestamp' => strval(time()), 'url' => $url ? : \Yii::$app->request->absoluteUrl, ]; return [ 'appId' => $this->app->appid, 'timestamp' => $params['timestamp'], 'nonceStr' => $params['noncestr'], 'signature' => $this->sign($params), 'signType' => 'sha1', ]; }
获取js接口调用配置 @since 0.0.1 @param {string} [$url] 调用js接口页面url @return {array} @example \Yii::$app->wechat->getJsapiConfig($url);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L1140-L1155
xiewulong/yii2-wechat
Manager.php
Manager.getJsapiTicket
public function getJsapiTicket() { $time = time(); if(empty($this->app->jsapi_ticket) || $this->app->jsapi_ticket_expired_at < $time) { $data = $this->getData('/cgi-bin/ticket/getticket', [ 'access_token' => $this->getAccessToken(), 'type' => 'jsapi', ]); if(isset($data['ticket']) && isset($data['expires_in'])) { $this->app->jsapi_ticket = $data['ticket']; $this->app->jsapi_ticket_expired_at = $time + $data['expires_in']; $this->app->save(); } } return $this->app->jsapi_ticket; }
php
public function getJsapiTicket() { $time = time(); if(empty($this->app->jsapi_ticket) || $this->app->jsapi_ticket_expired_at < $time) { $data = $this->getData('/cgi-bin/ticket/getticket', [ 'access_token' => $this->getAccessToken(), 'type' => 'jsapi', ]); if(isset($data['ticket']) && isset($data['expires_in'])) { $this->app->jsapi_ticket = $data['ticket']; $this->app->jsapi_ticket_expired_at = $time + $data['expires_in']; $this->app->save(); } } return $this->app->jsapi_ticket; }
获取js接口调用票据 @since 0.0.1 @return {string} @example \Yii::$app->wechat->getJsapiTicket();
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L1164-L1179
xiewulong/yii2-wechat
Manager.php
Manager.getAccessToken
public function getAccessToken() { $time = time(); if(empty($this->app->access_token) || $this->app->access_token_expired_at < $time) { $data = $this->getData('/cgi-bin/token', [ 'grant_type' => 'client_credential', 'appid' => $this->app->appid, 'secret' => $this->app->secret, ]); if(isset($data['access_token']) && isset($data['expires_in'])) { $this->app->access_token = $data['access_token']; $this->app->access_token_expired_at = $time + $data['expires_in']; $this->app->save(); } } return $this->app->access_token; }
php
public function getAccessToken() { $time = time(); if(empty($this->app->access_token) || $this->app->access_token_expired_at < $time) { $data = $this->getData('/cgi-bin/token', [ 'grant_type' => 'client_credential', 'appid' => $this->app->appid, 'secret' => $this->app->secret, ]); if(isset($data['access_token']) && isset($data['expires_in'])) { $this->app->access_token = $data['access_token']; $this->app->access_token_expired_at = $time + $data['expires_in']; $this->app->save(); } } return $this->app->access_token; }
获取接口调用凭据 @since 0.0.1 @return {string} @example \Yii::$app->wechat->getAccessToken();
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L1188-L1204
xiewulong/yii2-wechat
Manager.php
Manager.refreshUserAccessToken
public function refreshUserAccessToken($refresh_token) { $data = $this->getData('/sns/oauth2/refresh_token', [ 'appid' => $this->app->appid, 'grant_type' => 'refresh_token', 'refresh_token' => $refresh_token, ]); return $this->errcode == 0 ? $data : []; }
php
public function refreshUserAccessToken($refresh_token) { $data = $this->getData('/sns/oauth2/refresh_token', [ 'appid' => $this->app->appid, 'grant_type' => 'refresh_token', 'refresh_token' => $refresh_token, ]); return $this->errcode == 0 ? $data : []; }
刷新用户网页授权接口调用凭据 @since 0.0.1 @param {string} $refresh_token access_token刷新token @return {array} @example \Yii::$app->wechat->refreshUserAccessToken($refresh_token);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L1214-L1222
xiewulong/yii2-wechat
Manager.php
Manager.saveUser
public function saveUser($userinfo) { if(!isset($userinfo['openid'])) { return null; } if($user = $this->findUser($userinfo['openid'])) { return $user; } $user = new WechatUser; $user->appid = $this->app->appid; $user->openid = $userinfo['openid']; $user->name = $userinfo['nickname']; $user->sex = $userinfo['sex']; $user->language = $userinfo['language']; $user->city = $userinfo['city']; $user->province = $userinfo['province']; $user->country = $userinfo['country']; $user->headimgurl = $userinfo['headimgurl']; $user->privilegeList = $userinfo['privilege']; if(!$user->save()) { return null; } $this->refreshUser($user->id); return $user; }
php
public function saveUser($userinfo) { if(!isset($userinfo['openid'])) { return null; } if($user = $this->findUser($userinfo['openid'])) { return $user; } $user = new WechatUser; $user->appid = $this->app->appid; $user->openid = $userinfo['openid']; $user->name = $userinfo['nickname']; $user->sex = $userinfo['sex']; $user->language = $userinfo['language']; $user->city = $userinfo['city']; $user->province = $userinfo['province']; $user->country = $userinfo['country']; $user->headimgurl = $userinfo['headimgurl']; $user->privilegeList = $userinfo['privilege']; if(!$user->save()) { return null; } $this->refreshUser($user->id); return $user; }
保存用户 @since 0.0.1 @param {string} $openid OpenID @return {object} @example \Yii::$app->wechat->findUser($openid);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L1232-L1260
xiewulong/yii2-wechat
Manager.php
Manager.getUserInfoByCode
public function getUserInfoByCode($code) { $data = $this->getData('/sns/oauth2/access_token', [ 'appid' => $this->app->appid, 'secret' => $this->app->secret, 'grant_type' => 'authorization_code', 'code' => $code, ]); $user = []; if($this->errcode == 0) { $user['openid'] = $data['openid']; if($data['scope'] == 'snsapi_userinfo') { $data = $this->getData('/sns/userinfo', [ 'access_token' => $data['access_token'], 'openid' => $user['openid'], 'lang' => \Yii::$app->language, ]); if($this->errcode == 0) { $user = $data; } } } return $user; }
php
public function getUserInfoByCode($code) { $data = $this->getData('/sns/oauth2/access_token', [ 'appid' => $this->app->appid, 'secret' => $this->app->secret, 'grant_type' => 'authorization_code', 'code' => $code, ]); $user = []; if($this->errcode == 0) { $user['openid'] = $data['openid']; if($data['scope'] == 'snsapi_userinfo') { $data = $this->getData('/sns/userinfo', [ 'access_token' => $data['access_token'], 'openid' => $user['openid'], 'lang' => \Yii::$app->language, ]); if($this->errcode == 0) { $user = $data; } } } return $user; }
获取用户网页授权信息 @since 0.0.1 @param {string} $code 通过用户在网页授权后获取的code参数 @return {array} @example \Yii::$app->wechat->getUserInfo($code);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L1285-L1309
xiewulong/yii2-wechat
Manager.php
Manager.getUserAuthorizeCodeUrl
public function getUserAuthorizeCodeUrl($state = null, $scope = 'snsapi_base', $url = null) { return 'https://open.weixin.qq.com/connect/oauth2/authorize?' . http_build_query([ 'appid' => $this->app->appid, 'redirect_uri' => $url ? : \Yii::$app->request->absoluteUrl, 'response_type' => 'code', 'scope' => $scope, 'state' => $state, ]) . '#wechat_redirect'; }
php
public function getUserAuthorizeCodeUrl($state = null, $scope = 'snsapi_base', $url = null) { return 'https://open.weixin.qq.com/connect/oauth2/authorize?' . http_build_query([ 'appid' => $this->app->appid, 'redirect_uri' => $url ? : \Yii::$app->request->absoluteUrl, 'response_type' => 'code', 'scope' => $scope, 'state' => $state, ]) . '#wechat_redirect'; }
获取用户网页授权code跳转url @since 0.0.1 @param {string} [$state] 重定向后会带上state参数, 开发者可以填写a-zA-Z0-9的参数值, 最多128字节 @param {string} [$scope=snsapi_base] 应用授权作用域: snsapi_base(默认), snsapi_userinfo @param {string} [$url] 调用js接口页面url @return {string} @example \Yii::$app->wechat->getUserAuthorizeCodeUrl($state, $scope, $url);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L1321-L1329
xiewulong/yii2-wechat
Manager.php
Manager.generateRandomString
public function generateRandomString($len = 32) { $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $max = strlen($chars) - 1; $strArr = []; for($i = 0; $i < $len; $i++) { $strArr[] = $chars[mt_rand(0, $max)]; } return implode($strArr); }
php
public function generateRandomString($len = 32) { $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $max = strlen($chars) - 1; $strArr = []; for($i = 0; $i < $len; $i++) { $strArr[] = $chars[mt_rand(0, $max)]; } return implode($strArr); }
生成随机字符串 @since 0.0.1 @param {integer} [$len=32] 长度 @return {string} @example \Yii::$app->wechat->generateRandomString($len);
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L1350-L1360
xiewulong/yii2-wechat
Manager.php
Manager.saveFile
private function saveFile($data) { $fileupload = \Yii::createObject(\Yii::$app->components[$this->fileupload]); $fileinfo = $fileupload->createFile($data['extension']); $file = fopen($fileinfo['tmp'], 'wb'); fwrite($file, $data['content']); fclose($file); return $fileupload->finalFile($fileinfo); }
php
private function saveFile($data) { $fileupload = \Yii::createObject(\Yii::$app->components[$this->fileupload]); $fileinfo = $fileupload->createFile($data['extension']); $file = fopen($fileinfo['tmp'], 'wb'); fwrite($file, $data['content']); fclose($file); return $fileupload->finalFile($fileinfo); }
保存文件 @since 0.0.1 @param {array} $data 数据 @return {string}
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L1382-L1390
xiewulong/yii2-wechat
Manager.php
Manager.getData
private function getData($action, $query, $data = null) { $_result = $this->curl($this->getApiUrl($action, $query), $data); if(!$_result) { $this->errcode = '503'; $this->errmsg = '接口服务不可用'; } $result = json_decode($_result, true); if(json_last_error()) { if($extension = $this->getExtension($this->getMimeType($_result, true))) { $result = ['content' => $_result, 'extension' => $extension]; } else { $this->errcode = '503'; $this->errmsg = '数据不合法'; } } else if(isset($result['errcode']) && isset($result['errmsg'])) { $this->errcode = $result['errcode']; $this->errmsg = $this->getMessage($result['errmsg']); } return $result; }
php
private function getData($action, $query, $data = null) { $_result = $this->curl($this->getApiUrl($action, $query), $data); if(!$_result) { $this->errcode = '503'; $this->errmsg = '接口服务不可用'; } $result = json_decode($_result, true); if(json_last_error()) { if($extension = $this->getExtension($this->getMimeType($_result, true))) { $result = ['content' => $_result, 'extension' => $extension]; } else { $this->errcode = '503'; $this->errmsg = '数据不合法'; } } else if(isset($result['errcode']) && isset($result['errmsg'])) { $this->errcode = $result['errcode']; $this->errmsg = $this->getMessage($result['errmsg']); } return $result; }
获取数据 @since 0.0.1 @param {string} $action 接口名称 @param {array} $query 参数 @param {string|array} [$data] 数据 @return {array}
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L1401-L1423
xiewulong/yii2-wechat
Manager.php
Manager.getExtension
private function getExtension($mimetype) { if(preg_match('/^(image|audio|video)\/(.+)$/', $mimetype, $matches)) { $extension = $matches[2]; if(in_array($extension, ['jpeg', 'pjpeg'])) { $extension = 'jpg'; } else if(in_array($extension, ['mpeg4'])) { $extension = 'mp4'; } return $extension; } return null; }
php
private function getExtension($mimetype) { if(preg_match('/^(image|audio|video)\/(.+)$/', $mimetype, $matches)) { $extension = $matches[2]; if(in_array($extension, ['jpeg', 'pjpeg'])) { $extension = 'jpg'; } else if(in_array($extension, ['mpeg4'])) { $extension = 'mp4'; } return $extension; } return null; }
获取文件扩展名 @since 0.0.1 @param {string} $mimetype 文件MIME type @return {string}
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L1432-L1445
xiewulong/yii2-wechat
Manager.php
Manager.getMimeType
private function getMimeType($data, $stream = false) { $finfo = finfo_open(FILEINFO_MIME_TYPE); $mimetype = $stream ? finfo_buffer($finfo, $data) : finfo_file($finfo, $data); finfo_close($finfo); return $mimetype; }
php
private function getMimeType($data, $stream = false) { $finfo = finfo_open(FILEINFO_MIME_TYPE); $mimetype = $stream ? finfo_buffer($finfo, $data) : finfo_file($finfo, $data); finfo_close($finfo); return $mimetype; }
获取文件MIME type @since 0.0.1 @param {string} $data 数据 @param {boolean} $stream 数据流形式 @return {string}
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L1455-L1461
xiewulong/yii2-wechat
Manager.php
Manager.getApiUrl
private function getApiUrl($action, $query = []) { return $this->api . $action . (empty($query) ? '' : '?' . http_build_query($query)); }
php
private function getApiUrl($action, $query = []) { return $this->api . $action . (empty($query) ? '' : '?' . http_build_query($query)); }
获取接口完整访问地址 @since 0.0.1 @param {string} $action 接口名称 @param {array} [$query=[]] 参数 @return {string}
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L1471-L1473
xiewulong/yii2-wechat
Manager.php
Manager.getMessage
private function getMessage($status) { if($this->messages === false) { $this->messages = require(__DIR__ . '/messages.php'); } return isset($this->messages[$status]) ? $this->messages[$status] : "Error: $status"; }
php
private function getMessage($status) { if($this->messages === false) { $this->messages = require(__DIR__ . '/messages.php'); } return isset($this->messages[$status]) ? $this->messages[$status] : "Error: $status"; }
获取信息 @since 0.0.1 @param {string} $status 状态码 @return {string}
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L1493-L1499
xiewulong/yii2-wechat
Manager.php
Manager.curl
private function curl($url, $data = null, $useragent = null) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); if(!empty($data)) { curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } if(!empty($useragent)) { curl_setopt($curl, CURLOPT_USERAGENT, $useragent); } $result = curl_exec($curl); curl_close($curl); return $result; }
php
private function curl($url, $data = null, $useragent = null) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); if(!empty($data)) { curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } if(!empty($useragent)) { curl_setopt($curl, CURLOPT_USERAGENT, $useragent); } $result = curl_exec($curl); curl_close($curl); return $result; }
curl远程获取数据方法 @since 0.0.1 @param {string} $url 请求地址 @param {string|array} [$data] post数据 @param {string} [$useragent] 模拟浏览器用户代理信息 @return {array}
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L1510-L1526
PandaPlatform/jar
Model/Content/XmlContent.php
XmlContent.setDOMElementPayload
public function setDOMElementPayload(DOMElement $element) { $this->setPayload($element->ownerDocument->saveXML($element)); return $this; }
php
public function setDOMElementPayload(DOMElement $element) { $this->setPayload($element->ownerDocument->saveXML($element)); return $this; }
@param DOMElement $element @return $this
https://github.com/PandaPlatform/jar/blob/56b6d8687a565482f8315f3dde4cf08d6fc0e2b3/Model/Content/XmlContent.php#L42-L47
znframework/package-helpers
Cleaner.php
Cleaner.data
public static function data($searchData, $cleanWord) { if( length($cleanWord) > length($searchData) ) { throw new LogicException('[Cleaner::data()] -> 3.($cleanWord) parameter not be longer than 2.($searchData) parameter!'); } if( ! is_array($searchData) ) { $result = str_replace($cleanWord, '', $searchData); } else { if( ! is_array($cleanWord) ) { $cleanWordArray[] = $cleanWord; } else { $cleanWordArray = $cleanWord; } $result = array_diff($searchData, $cleanWordArray); } return $result; }
php
public static function data($searchData, $cleanWord) { if( length($cleanWord) > length($searchData) ) { throw new LogicException('[Cleaner::data()] -> 3.($cleanWord) parameter not be longer than 2.($searchData) parameter!'); } if( ! is_array($searchData) ) { $result = str_replace($cleanWord, '', $searchData); } else { if( ! is_array($cleanWord) ) { $cleanWordArray[] = $cleanWord; } else { $cleanWordArray = $cleanWord; } $result = array_diff($searchData, $cleanWordArray); } return $result; }
Clean Data @param mixed $searchData @param mixed $cleanWord @return mixed
https://github.com/znframework/package-helpers/blob/c78502263cdda5c14626a1abf7fc7e02dd2bd57d/Cleaner.php#L24-L50
oscarpalmer/shelf
src/oscarpalmer/Shelf/Blob.php
Blob.delete
public function delete($key) : Blob { if ($this->offsetExists($key)) { $this->offsetUnset($key); } return $this; }
php
public function delete($key) : Blob { if ($this->offsetExists($key)) { $this->offsetUnset($key); } return $this; }
Delete value for key in Blob. @param mixed $key Key to delete. @return Blob Blob object for optional chaining.
https://github.com/oscarpalmer/shelf/blob/47bccf7fd8f1750defe1f2805480a6721f1a0e79/src/oscarpalmer/Shelf/Blob.php#L28-L35
iwyg/xmlconf
src/Thapp/XmlConf/XmlConfServiceProvider.php
XmlConfServiceProvider.getSchemaPath
public function getSchemaPath($reader, $base) { return sprintf('%s/%s/%s/Schema/%s.xsd', dirname(app_path()), $base, ucfirst(camel_case($reader)), $reader); }
php
public function getSchemaPath($reader, $base) { return sprintf('%s/%s/%s/Schema/%s.xsd', dirname(app_path()), $base, ucfirst(camel_case($reader)), $reader); }
getSchamePath @param string $reader @access public @return string
https://github.com/iwyg/xmlconf/blob/1d8a657073f3fd46dacfb6bf5d173f9d5283661b/src/Thapp/XmlConf/XmlConfServiceProvider.php#L75-L78
iwyg/xmlconf
src/Thapp/XmlConf/XmlConfServiceProvider.php
XmlConfServiceProvider.checkBaseDir
private function checkBaseDir($reader, array $base) { if (!isset($base[$reader]) || !is_dir(dirname(app_path()) . '/' . $base[$reader])) { throw new \RuntimeException('Either a basedir is not set or basedir is not a directory'); } }
php
private function checkBaseDir($reader, array $base) { if (!isset($base[$reader]) || !is_dir(dirname(app_path()) . '/' . $base[$reader])) { throw new \RuntimeException('Either a basedir is not set or basedir is not a directory'); } }
checkBaseDir @param string $reader @param array $base @throws \RuntimeException @access private @return void
https://github.com/iwyg/xmlconf/blob/1d8a657073f3fd46dacfb6bf5d173f9d5283661b/src/Thapp/XmlConf/XmlConfServiceProvider.php#L102-L107
iwyg/xmlconf
src/Thapp/XmlConf/XmlConfServiceProvider.php
XmlConfServiceProvider.regsiterCommands
protected function regsiterCommands() { $this->app['command.xmlconf.warmup'] = $this->app->share( function ($app) { return new Console\XmlConfWarmupCommand($app, $app['config']->get('xmlconf::namespaces')); } ); $this->commands( 'command.xmlconf.warmup' ); }
php
protected function regsiterCommands() { $this->app['command.xmlconf.warmup'] = $this->app->share( function ($app) { return new Console\XmlConfWarmupCommand($app, $app['config']->get('xmlconf::namespaces')); } ); $this->commands( 'command.xmlconf.warmup' ); }
regsiterCommands @access protected @return void
https://github.com/iwyg/xmlconf/blob/1d8a657073f3fd46dacfb6bf5d173f9d5283661b/src/Thapp/XmlConf/XmlConfServiceProvider.php#L115-L130
iwyg/xmlconf
src/Thapp/XmlConf/XmlConfServiceProvider.php
XmlConfServiceProvider.regsiterConfigDrivers
protected function regsiterConfigDrivers() { // register xml config dirvers $me = $this; $base = $this->app['config']->get('xmlconf::basedir', array()); $cacheDriver = $this->app['config']->get('cache.driver', 'file'); foreach ($this->app['config']->get('xmlconf::namespaces', array()) as $reader => $namespace) { $this->checkBaseDir($reader, $base); $this->app['xmlconf.' . $reader] = $this->app->share(function ($app) use ($me, $base, $reader, $namespace, $cacheDriver) { $class = $me->getReaderClass($reader, $namespace); $cache = new Cache\Cache($app['cache']->driver($cacheDriver), $reader); $xmlreader = new $class( $cache, $me->getSimpleXmlClass($reader, $namespace), $me->getConfPath($reader), $me->getSchemaPath($reader, $base[$reader]) ); return $xmlreader; }); } }
php
protected function regsiterConfigDrivers() { // register xml config dirvers $me = $this; $base = $this->app['config']->get('xmlconf::basedir', array()); $cacheDriver = $this->app['config']->get('cache.driver', 'file'); foreach ($this->app['config']->get('xmlconf::namespaces', array()) as $reader => $namespace) { $this->checkBaseDir($reader, $base); $this->app['xmlconf.' . $reader] = $this->app->share(function ($app) use ($me, $base, $reader, $namespace, $cacheDriver) { $class = $me->getReaderClass($reader, $namespace); $cache = new Cache\Cache($app['cache']->driver($cacheDriver), $reader); $xmlreader = new $class( $cache, $me->getSimpleXmlClass($reader, $namespace), $me->getConfPath($reader), $me->getSchemaPath($reader, $base[$reader]) ); return $xmlreader; }); } }
regsiterConfigDrivers @access protected @return void
https://github.com/iwyg/xmlconf/blob/1d8a657073f3fd46dacfb6bf5d173f9d5283661b/src/Thapp/XmlConf/XmlConfServiceProvider.php#L138-L165
as3io/symfony-data-importer
src/Console/Import.php
Import.doCommandImportSetUp
final protected function doCommandImportSetUp() { $this->writeln('Executing <info>setup</info> tasks', true); // $this->updateSchema(); $this->importManager->setUp(); $this->writeln('Startup tasks complete.', true, true); }
php
final protected function doCommandImportSetUp() { $this->writeln('Executing <info>setup</info> tasks', true); // $this->updateSchema(); $this->importManager->setUp(); $this->writeln('Startup tasks complete.', true, true); }
Performs startup tasks
https://github.com/as3io/symfony-data-importer/blob/33383e38f20f6b7a4b83da619bd028ac84ced579/src/Console/Import.php#L247-L255
as3io/symfony-data-importer
src/Console/Import.php
Import.doCommandImport
final protected function doCommandImport() { $this->writeln('Starting Import', true, true); $this->indent(); foreach ($this->importManager->getConfiguration()->getSegments() as $segment) { $this->importSegment($segment); } $this->outdent(); $this->writeln('<info>Import complete!</info>', true, true); }
php
final protected function doCommandImport() { $this->writeln('Starting Import', true, true); $this->indent(); foreach ($this->importManager->getConfiguration()->getSegments() as $segment) { $this->importSegment($segment); } $this->outdent(); $this->writeln('<info>Import complete!</info>', true, true); }
The main import loop
https://github.com/as3io/symfony-data-importer/blob/33383e38f20f6b7a4b83da619bd028ac84ced579/src/Console/Import.php#L260-L271
as3io/symfony-data-importer
src/Console/Import.php
Import.doCommandImportTearDown
final protected function doCommandImportTearDown() { $this->writeln('Executing <info>teardown</info> tasks', false, true); $this->indent(); $this->subscriberPass(); $this->outdent(); $this->writeln('Teardown tasks complete.', false, true); }
php
final protected function doCommandImportTearDown() { $this->writeln('Executing <info>teardown</info> tasks', false, true); $this->indent(); $this->subscriberPass(); $this->outdent(); $this->writeln('Teardown tasks complete.', false, true); }
Performs teardown tasks
https://github.com/as3io/symfony-data-importer/blob/33383e38f20f6b7a4b83da619bd028ac84ced579/src/Console/Import.php#L276-L285
iron-bound-designs/wp-notifications
src/Template/Manager.php
Manager.listen
public function listen( Listener $listener ) { if ( isset( $this->listeners[ $listener->get_tag() ] ) ) { return false; } $this->listeners[ $listener->get_tag() ] = $listener; return true; }
php
public function listen( Listener $listener ) { if ( isset( $this->listeners[ $listener->get_tag() ] ) ) { return false; } $this->listeners[ $listener->get_tag() ] = $listener; return true; }
Listen for a template tag. @since 1.0 @param Listener $listener @return bool
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Template/Manager.php#L50-L59
iron-bound-designs/wp-notifications
src/Template/Manager.php
Manager.get_listener
public function get_listener( $tag ) { return isset( $this->listeners[ $tag ] ) ? $this->listeners[ $tag ] : new Null_Listener(); }
php
public function get_listener( $tag ) { return isset( $this->listeners[ $tag ] ) ? $this->listeners[ $tag ] : new Null_Listener(); }
Get a listener for a certain tag. @param string $tag @return Listener|Null_Listener Null Listener is returned if listener for given tag does not exist.
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Template/Manager.php#L68-L70
iron-bound-designs/wp-notifications
src/Template/Manager.php
Manager.render_tags
public function render_tags( array $data_sources ) { $replaced = array(); foreach ( $this->get_listeners() as $tag => $listener ) { $params = $listener->get_callback_reflection()->getParameters(); $args = array(); foreach ( $params as $param ) { $found = false; foreach ( $data_sources as $name => $data_source ) { if ( is_object( $data_source ) && ( $class = $param->getClass() ) !== null && $class->isInstance( $data_source ) ) { $args[] = $data_source; $found = true; } elseif ( $param->getName() === $name ) { if ( isset( $class ) ) { throw new \BadMethodCallException( "Data source '$name' does not match type of required parameter '{$param->getName()}'. Required type: '{$class->getName()}''", 1 ); } $args[] = $data_source; $found = true; } if ( $found ) { break; } } if ( $found ) { continue; } if ( $param->isDefaultValueAvailable() ) { $args[] = $param->getDefaultValue(); } else { throw new \BadMethodCallException( "Not all required parameters were provided. Required: '{$param->getName()}'.'", 2 ); } } $replaced[ $tag ] = $listener->render( $args ); } return $replaced; }
php
public function render_tags( array $data_sources ) { $replaced = array(); foreach ( $this->get_listeners() as $tag => $listener ) { $params = $listener->get_callback_reflection()->getParameters(); $args = array(); foreach ( $params as $param ) { $found = false; foreach ( $data_sources as $name => $data_source ) { if ( is_object( $data_source ) && ( $class = $param->getClass() ) !== null && $class->isInstance( $data_source ) ) { $args[] = $data_source; $found = true; } elseif ( $param->getName() === $name ) { if ( isset( $class ) ) { throw new \BadMethodCallException( "Data source '$name' does not match type of required parameter '{$param->getName()}'. Required type: '{$class->getName()}''", 1 ); } $args[] = $data_source; $found = true; } if ( $found ) { break; } } if ( $found ) { continue; } if ( $param->isDefaultValueAvailable() ) { $args[] = $param->getDefaultValue(); } else { throw new \BadMethodCallException( "Not all required parameters were provided. Required: '{$param->getName()}'.'", 2 ); } } $replaced[ $tag ] = $listener->render( $args ); } return $replaced; }
Return an array of the rendered tags. @since 1.0 @param array $data_sources @return array @throws \BadMethodCallException
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Template/Manager.php#L107-L159
jelix/file-utilities
lib/Directory.php
Directory.create
public static function create($dir, $chmod = null) { if (!file_exists($dir)) { if ($chmod === null) { $chmod = self::$defaultChmod; } mkdir($dir, $chmod, true); // php mkdir apply umask on the given mode, so we must to // do a chmod manually. chmod($dir, $chmod); return true; } return false; }
php
public static function create($dir, $chmod = null) { if (!file_exists($dir)) { if ($chmod === null) { $chmod = self::$defaultChmod; } mkdir($dir, $chmod, true); // php mkdir apply umask on the given mode, so we must to // do a chmod manually. chmod($dir, $chmod); return true; } return false; }
create a directory. @return bool false if the directory did already exist
https://github.com/jelix/file-utilities/blob/05fd364860ed147e6367de9db3dc544f58c5a05c/lib/Directory.php#L26-L40
jelix/file-utilities
lib/Directory.php
Directory.remove
public static function remove($path, $deleteDir = true) { // minimum security check if ($path == '' || $path == '/' || $path == DIRECTORY_SEPARATOR) { throw new \InvalidArgumentException('The root cannot be removed !!'); } if (!file_exists($path)) { return true; } $dir = new \DirectoryIterator($path); foreach ($dir as $dirContent) { // file deletion if ($dirContent->isFile() || $dirContent->isLink()) { unlink($dirContent->getPathName()); } else { // recursive directory deletion if (!$dirContent->isDot() && $dirContent->isDir()) { self::remove($dirContent->getPathName()); } } } unset($dir); unset($dirContent); // removes the parent directory if ($deleteDir) { rmdir($path); } }
php
public static function remove($path, $deleteDir = true) { // minimum security check if ($path == '' || $path == '/' || $path == DIRECTORY_SEPARATOR) { throw new \InvalidArgumentException('The root cannot be removed !!'); } if (!file_exists($path)) { return true; } $dir = new \DirectoryIterator($path); foreach ($dir as $dirContent) { // file deletion if ($dirContent->isFile() || $dirContent->isLink()) { unlink($dirContent->getPathName()); } else { // recursive directory deletion if (!$dirContent->isDot() && $dirContent->isDir()) { self::remove($dirContent->getPathName()); } } } unset($dir); unset($dirContent); // removes the parent directory if ($deleteDir) { rmdir($path); } }
Recursive function deleting a directory. @param string $path The path of the directory to remove recursively @param bool $deleteDir If the path must be deleted too @author Loic Mathaud
https://github.com/jelix/file-utilities/blob/05fd364860ed147e6367de9db3dc544f58c5a05c/lib/Directory.php#L50-L80
jelix/file-utilities
lib/Directory.php
Directory.removeExcept
public static function removeExcept($path, $except, $deleteDir = true) { if (!is_array($except) || !count($except)) { throw new \InvalidArgumentException('list of exception is not an array or is empty'); } if ($path == '' || $path == '/' || $path == DIRECTORY_SEPARATOR) { throw new \InvalidArgumentException('The root cannot be removed !!'); } if (!file_exists($path)) { return true; } $allIsDeleted = true; $dir = new \DirectoryIterator($path); foreach ($dir as $dirContent) { // test if the basename matches one of patterns $exception = false; foreach ($except as $pattern) { if ($pattern[0] == '*') { // for pattern like *.foo if ($dirContent->getBasename() != $dirContent->getBasename(substr($pattern, 1))) { $allIsDeleted = false; $exception = true; break; } } elseif ($pattern == $dirContent->getBasename()) { $allIsDeleted = false; $exception = true; break; } } if ($exception) { continue; } // file deletion if ($dirContent->isFile() || $dirContent->isLink()) { unlink($dirContent->getPathName()); } else { // recursive directory deletion if (!$dirContent->isDot() && $dirContent->isDir()) { $removed = self::removeExcept($dirContent->getPathName(), $except, true); if (!$removed) { $allIsDeleted = false; } } } } unset($dir); unset($dirContent); // removes the parent directory if ($deleteDir && $allIsDeleted) { rmdir($path); } return $allIsDeleted; }
php
public static function removeExcept($path, $except, $deleteDir = true) { if (!is_array($except) || !count($except)) { throw new \InvalidArgumentException('list of exception is not an array or is empty'); } if ($path == '' || $path == '/' || $path == DIRECTORY_SEPARATOR) { throw new \InvalidArgumentException('The root cannot be removed !!'); } if (!file_exists($path)) { return true; } $allIsDeleted = true; $dir = new \DirectoryIterator($path); foreach ($dir as $dirContent) { // test if the basename matches one of patterns $exception = false; foreach ($except as $pattern) { if ($pattern[0] == '*') { // for pattern like *.foo if ($dirContent->getBasename() != $dirContent->getBasename(substr($pattern, 1))) { $allIsDeleted = false; $exception = true; break; } } elseif ($pattern == $dirContent->getBasename()) { $allIsDeleted = false; $exception = true; break; } } if ($exception) { continue; } // file deletion if ($dirContent->isFile() || $dirContent->isLink()) { unlink($dirContent->getPathName()); } else { // recursive directory deletion if (!$dirContent->isDot() && $dirContent->isDir()) { $removed = self::removeExcept($dirContent->getPathName(), $except, true); if (!$removed) { $allIsDeleted = false; } } } } unset($dir); unset($dirContent); // removes the parent directory if ($deleteDir && $allIsDeleted) { rmdir($path); } return $allIsDeleted; }
Recursive function deleting all files into a directory except those indicated. @param string $path The path of the directory to remove recursively @param array $except filenames and suffix of filename, for files to NOT delete @param bool $deleteDir If the path must be deleted too @return bool true if all the content has been removed @author Loic Mathaud
https://github.com/jelix/file-utilities/blob/05fd364860ed147e6367de9db3dc544f58c5a05c/lib/Directory.php#L93-L150
jelix/file-utilities
lib/Directory.php
Directory.copy
static function copy($srcDir, $destDir, $overwrite = true) { Directory::create($destDir); $dir = new \DirectoryIterator($srcDir); foreach ($dir as $dirContent) { if ($dirContent->isFile() || $dirContent->isLink()) { $target = $destDir.'/'.$dirContent->getFilename(); if ($overwrite || !file_exists($target)) { copy($dirContent->getPathName(), $target); } } else if (!$dirContent->isDot() && $dirContent->isDir()) { self::copy($dirContent->getPathName(), $destDir.'/'.$dirContent->getFilename(), $overwrite); } } }
php
static function copy($srcDir, $destDir, $overwrite = true) { Directory::create($destDir); $dir = new \DirectoryIterator($srcDir); foreach ($dir as $dirContent) { if ($dirContent->isFile() || $dirContent->isLink()) { $target = $destDir.'/'.$dirContent->getFilename(); if ($overwrite || !file_exists($target)) { copy($dirContent->getPathName(), $target); } } else if (!$dirContent->isDot() && $dirContent->isDir()) { self::copy($dirContent->getPathName(), $destDir.'/'.$dirContent->getFilename(), $overwrite); } } }
Copy a content directory into an other @param string $srcDir the directory from which content will be copied @param string $destDir the directory in which content will be copied @param boolean $overwrite set to false to not overwrite existing files in the target directory
https://github.com/jelix/file-utilities/blob/05fd364860ed147e6367de9db3dc544f58c5a05c/lib/Directory.php#L159-L173
4devs/serializer
Mapping/PropertyMetadata.php
PropertyMetadata.serialize
public function serialize() { return serialize([ $this->type, $this->accessor, $this->visibility, $this->advancedVisibility, $this->nullable, $this->nameConverter, parent::serialize(), ]); }
php
public function serialize() { return serialize([ $this->type, $this->accessor, $this->visibility, $this->advancedVisibility, $this->nullable, $this->nameConverter, parent::serialize(), ]); }
{@inheritdoc}
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Mapping/PropertyMetadata.php#L151-L162
4devs/serializer
Mapping/PropertyMetadata.php
PropertyMetadata.unserialize
public function unserialize($str) { list( $this->type, $this->accessor, $this->visibility, $this->advancedVisibility, $this->nullable, $this->nameConverter, $parentStr) = unserialize($str); parent::unserialize($parentStr); }
php
public function unserialize($str) { list( $this->type, $this->accessor, $this->visibility, $this->advancedVisibility, $this->nullable, $this->nameConverter, $parentStr) = unserialize($str); parent::unserialize($parentStr); }
{@inheritdoc}
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Mapping/PropertyMetadata.php#L167-L178
brick/validation
src/Validator/TimeValidator.php
TimeValidator.validate
protected function validate(string $value) : void { if (preg_match('/^([0-9]{2})\:([0-9]{2})(?:\:([0-9]{2}))?$/', $value, $matches) !== 1) { $this->addFailureMessage('validator.time.invalid-format'); } else { if ($matches[1] > 23 || $matches[2] > 59 || (isset($matches[3]) && $matches[3] > 59)) { $this->addFailureMessage('validator.time.invalid-time'); } } }
php
protected function validate(string $value) : void { if (preg_match('/^([0-9]{2})\:([0-9]{2})(?:\:([0-9]{2}))?$/', $value, $matches) !== 1) { $this->addFailureMessage('validator.time.invalid-format'); } else { if ($matches[1] > 23 || $matches[2] > 59 || (isset($matches[3]) && $matches[3] > 59)) { $this->addFailureMessage('validator.time.invalid-time'); } } }
{@inheritdoc}
https://github.com/brick/validation/blob/b33593f75df80530417007bde97c4772807563ab/src/Validator/TimeValidator.php#L28-L37
Boolive/Core
utils/Transform.php
Transform.reset
function reset() { $this->_transforms = array(); $this->_transforms_str = ''; $this->_info = null; if ($this->_handler) imagedestroy($this->_handler); $this->_handler = null; return $this; }
php
function reset() { $this->_transforms = array(); $this->_transforms_str = ''; $this->_info = null; if ($this->_handler) imagedestroy($this->_handler); $this->_handler = null; return $this; }
Сброс трансформаций @return $this
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/utils/Transform.php#L72-L80
Boolive/Core
utils/Transform.php
Transform.handler
function handler() { if (!isset($this->_handler)){ $file = $this->getDir().'/'.$this->file; switch ($this->ext()){ case 'gif': $this->_handler = @imagecreatefromgif($file); break; case 'png': $this->_handler = @imagecreatefrompng($file); break; case 'jpg': $this->_handler = @imagecreatefromjpeg($file); break; default: throw new \Exception('Не поддерживаем тип файла-изображения'); } } return $this->_handler; }
php
function handler() { if (!isset($this->_handler)){ $file = $this->getDir().'/'.$this->file; switch ($this->ext()){ case 'gif': $this->_handler = @imagecreatefromgif($file); break; case 'png': $this->_handler = @imagecreatefrompng($file); break; case 'jpg': $this->_handler = @imagecreatefromjpeg($file); break; default: throw new \Exception('Не поддерживаем тип файла-изображения'); } } return $this->_handler; }
Ресурс изображения для функций GD @return resource @throws \Exception
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/utils/Transform.php#L87-L106
Boolive/Core
utils/Transform.php
Transform.info
function info() { if (empty($this->_info)){ $file = $this->getDir().'/'.$this->file; if (is_file($file) && ($info = getimagesize($file))){ $ext = array(1 => 'gif', 2 => 'jpg', 3 => 'png', 4 => 'swf', 5 => 'psd', 6 => 'bmp', 7 => 'tiff', 8 => 'tiff', 9 => 'jpc', 10 => 'jp2', 11 => 'jpx', 12 => 'jb2', 13 => 'swc', 14 => 'iff', 15 => 'wbmp', 16 => 'xbmp' ); $this->_info = array( 'width' => $info[0], 'height' => $info[1], 'ext' => $ext[$info[2]], 'quality' => 100 ); if (empty($this->_convert)) $this->_convert = $ext[$info[2]]; } } return $this->_info; }
php
function info() { if (empty($this->_info)){ $file = $this->getDir().'/'.$this->file; if (is_file($file) && ($info = getimagesize($file))){ $ext = array(1 => 'gif', 2 => 'jpg', 3 => 'png', 4 => 'swf', 5 => 'psd', 6 => 'bmp', 7 => 'tiff', 8 => 'tiff', 9 => 'jpc', 10 => 'jp2', 11 => 'jpx', 12 => 'jb2', 13 => 'swc', 14 => 'iff', 15 => 'wbmp', 16 => 'xbmp' ); $this->_info = array( 'width' => $info[0], 'height' => $info[1], 'ext' => $ext[$info[2]], 'quality' => 100 ); if (empty($this->_convert)) $this->_convert = $ext[$info[2]]; } } return $this->_info; }
Информация об изображении @return array
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/utils/Transform.php#L112-L130
Boolive/Core
utils/Transform.php
Transform.resize
function resize($width, $height, $fit = Transform::FIT_OUT_LEFT_TOP, $scale = Transform::SCALE_ANY, $do = false) { if (is_string($fit)) $fit = constant('self::'. $fit); if (is_string($scale)) $scale = constant('self::'. $scale); $width = max(0, min($width, 1500)); $height = max(0, min($height, 1500)); $fit = intval($fit); $scale = intval($scale); if (!$do){ $this->_transforms[] = array('resize', array($width, $height, $fit, $scale, true)); $this->_transforms_str.= 'resize('.$width.'x'.$height.'x'.$fit.'x'.$scale.')'; }else{ if ($handler = $this->handler()){ // Выполение масштабирования $src = array('x' => 0, 'y' => 0, 'w' => $this->width(), 'h' => $this->height()); $new = array('x' => 0, 'y' => 0, 'w' => $width, 'h' => $height); // $do_scale = false; $dw = $src['w'] - $new['w']; $dh = $src['h'] - $new['h']; // Коррекция масштабирования $can_scale = function($d) use($scale){ // Только увеличивать if ($scale == Transform::SCALE_UP){ return min($d, 0); }else // Только уменьшать if ($scale == Transform::SCALE_DOWN){ return max($d, 0); } return $d; }; if ($new['w'] != 0 && $new['h'] != 0 || $new['h']!=$new['w']){ // Автоматически ширена или высота if (($new['w'] == 0 || $new['h'] == 0) && ($do_scale = $can_scale($dw))){ $ratio = $src['w'] / $src['h']; if ($new['w'] == 0){ $new['w'] = round($new['h'] * $ratio); }else{ $new['h'] = round($new['w'] / $ratio); } }else // Максимальное изменение if ($fit === self::FIT_IN){ $ratio = $src['w'] / $src['h']; if ($dw > $dh && ($do_scale = $can_scale($dw))){ $new['h'] = round($new['w'] / $ratio); }else if ($dw < $dh && ($do_scale = $can_scale($dh))){ $new['w'] = round($new['h'] * $ratio); }else if ($dw == $dh){ $do_scale = $can_scale($dw); } }else // Минимальное изменение if ($fit >= self::FIT_OUT_LEFT_TOP && $fit <= self::FIT_OUT_RIGHT_BOTTOM){ $ratio = $new['w'] / $new['h']; if ($dw < $dh && ($do_scale = $can_scale($dw))){ $last = $src['h']; $src['h'] = round($src['w'] / $ratio); if ($fit & (self::FIT_OUT_LEFT_BOTTOM | self::FIT_OUT_CENTER_BOTTOM | self::FIT_OUT_RIGHT_BOTTOM)){ $src['y'] = $last - $src['h']; }else if ($fit & (self::FIT_OUT_LEFT_MIDDLE | self::FIT_OUT_CENTER_MIDDLE | self::FIT_OUT_RIGHT_MIDDLE)){ $src['y'] = round(($last - $src['h']) / 2); } }else if ($dw > $dh && ($do_scale = $can_scale($dh))){ $last = $src['w']; $src['w'] = round($src['h'] * $ratio); if ($fit & (self::FIT_OUT_RIGHT_TOP | self::FIT_OUT_RIGHT_MIDDLE | self::FIT_OUT_RIGHT_BOTTOM)){ $src['x'] = $last - $src['w']; }else if ($fit & (self::FIT_OUT_CENTER_TOP | self::FIT_OUT_CENTER_MIDDLE | self::FIT_OUT_CENTER_BOTTOM)){ $src['x'] = round(($last - $src['w']) / 2); } }else if ($dw == $dh){ $do_scale = $can_scale($dw); } } if ($do_scale){ $img = imagecreatetruecolor($new['w'], $new['h']); imagealphablending($img, false); imagesavealpha($img, true); imagecopyresampled($img, $this->_handler, $new['x'], $new['y'], $src['x'], $src['y'], $new['w'], $new['h'], $src['w'], $src['h']); imagedestroy($this->_handler); $this->_handler = $img; $this->_info['width'] = $new['w']; $this->_info['height'] = $new['h']; } } } } return $this; }
php
function resize($width, $height, $fit = Transform::FIT_OUT_LEFT_TOP, $scale = Transform::SCALE_ANY, $do = false) { if (is_string($fit)) $fit = constant('self::'. $fit); if (is_string($scale)) $scale = constant('self::'. $scale); $width = max(0, min($width, 1500)); $height = max(0, min($height, 1500)); $fit = intval($fit); $scale = intval($scale); if (!$do){ $this->_transforms[] = array('resize', array($width, $height, $fit, $scale, true)); $this->_transforms_str.= 'resize('.$width.'x'.$height.'x'.$fit.'x'.$scale.')'; }else{ if ($handler = $this->handler()){ // Выполение масштабирования $src = array('x' => 0, 'y' => 0, 'w' => $this->width(), 'h' => $this->height()); $new = array('x' => 0, 'y' => 0, 'w' => $width, 'h' => $height); // $do_scale = false; $dw = $src['w'] - $new['w']; $dh = $src['h'] - $new['h']; // Коррекция масштабирования $can_scale = function($d) use($scale){ // Только увеличивать if ($scale == Transform::SCALE_UP){ return min($d, 0); }else // Только уменьшать if ($scale == Transform::SCALE_DOWN){ return max($d, 0); } return $d; }; if ($new['w'] != 0 && $new['h'] != 0 || $new['h']!=$new['w']){ // Автоматически ширена или высота if (($new['w'] == 0 || $new['h'] == 0) && ($do_scale = $can_scale($dw))){ $ratio = $src['w'] / $src['h']; if ($new['w'] == 0){ $new['w'] = round($new['h'] * $ratio); }else{ $new['h'] = round($new['w'] / $ratio); } }else // Максимальное изменение if ($fit === self::FIT_IN){ $ratio = $src['w'] / $src['h']; if ($dw > $dh && ($do_scale = $can_scale($dw))){ $new['h'] = round($new['w'] / $ratio); }else if ($dw < $dh && ($do_scale = $can_scale($dh))){ $new['w'] = round($new['h'] * $ratio); }else if ($dw == $dh){ $do_scale = $can_scale($dw); } }else // Минимальное изменение if ($fit >= self::FIT_OUT_LEFT_TOP && $fit <= self::FIT_OUT_RIGHT_BOTTOM){ $ratio = $new['w'] / $new['h']; if ($dw < $dh && ($do_scale = $can_scale($dw))){ $last = $src['h']; $src['h'] = round($src['w'] / $ratio); if ($fit & (self::FIT_OUT_LEFT_BOTTOM | self::FIT_OUT_CENTER_BOTTOM | self::FIT_OUT_RIGHT_BOTTOM)){ $src['y'] = $last - $src['h']; }else if ($fit & (self::FIT_OUT_LEFT_MIDDLE | self::FIT_OUT_CENTER_MIDDLE | self::FIT_OUT_RIGHT_MIDDLE)){ $src['y'] = round(($last - $src['h']) / 2); } }else if ($dw > $dh && ($do_scale = $can_scale($dh))){ $last = $src['w']; $src['w'] = round($src['h'] * $ratio); if ($fit & (self::FIT_OUT_RIGHT_TOP | self::FIT_OUT_RIGHT_MIDDLE | self::FIT_OUT_RIGHT_BOTTOM)){ $src['x'] = $last - $src['w']; }else if ($fit & (self::FIT_OUT_CENTER_TOP | self::FIT_OUT_CENTER_MIDDLE | self::FIT_OUT_CENTER_BOTTOM)){ $src['x'] = round(($last - $src['w']) / 2); } }else if ($dw == $dh){ $do_scale = $can_scale($dw); } } if ($do_scale){ $img = imagecreatetruecolor($new['w'], $new['h']); imagealphablending($img, false); imagesavealpha($img, true); imagecopyresampled($img, $this->_handler, $new['x'], $new['y'], $src['x'], $src['y'], $new['w'], $new['h'], $src['w'], $src['h']); imagedestroy($this->_handler); $this->_handler = $img; $this->_info['width'] = $new['w']; $this->_info['height'] = $new['h']; } } } } return $this; }
Изменение размера @param int $width Требуемая ширена изображения @param int $height Требуемая высота изображения @param int $fit Тип масштабирования. Указывается константами Transform::FIT_* @param int $scale Направление масштабирования. Указывается константами Transform::SCALE_* @param bool $do Признак, выполнять трансформацию (true) или отложить до результата (пути на файл) @return $this
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/utils/Transform.php#L167-L263
Boolive/Core
utils/Transform.php
Transform.crop
function crop($left, $top, $right, $bottom, $do = false) { $left = intval($left); $top = intval($top); $right = intval($right); $bottom = intval($bottom); if (!$do){ $this->_transforms[] = array('crop', array($left, $top, $right, $bottom, true)); $this->_transforms_str.='crop('.$left.'x'.$top.'x'.$right.'x'.$bottom.')'; }else{ // Выполение обрезания if ($right < $left) { list($left, $right) = array($right, $left); } if ($bottom < $top) { list($top, $bottom) = array($bottom, $top); } $crop_width = $right - $left; $crop_height = $bottom - $top; $new = imagecreatetruecolor($crop_width, $crop_height); imagealphablending($new, false); imagesavealpha($new, true); imagecopyresampled($new, $this->handler(), 0, 0, $left, $top, $crop_width, $crop_height, $crop_width, $crop_height); $this->_info['width'] = $crop_width; $this->_info['height'] = $crop_height; imagedestroy($this->_handler); $this->_handler = $new; } return $this; }
php
function crop($left, $top, $right, $bottom, $do = false) { $left = intval($left); $top = intval($top); $right = intval($right); $bottom = intval($bottom); if (!$do){ $this->_transforms[] = array('crop', array($left, $top, $right, $bottom, true)); $this->_transforms_str.='crop('.$left.'x'.$top.'x'.$right.'x'.$bottom.')'; }else{ // Выполение обрезания if ($right < $left) { list($left, $right) = array($right, $left); } if ($bottom < $top) { list($top, $bottom) = array($bottom, $top); } $crop_width = $right - $left; $crop_height = $bottom - $top; $new = imagecreatetruecolor($crop_width, $crop_height); imagealphablending($new, false); imagesavealpha($new, true); imagecopyresampled($new, $this->handler(), 0, 0, $left, $top, $crop_width, $crop_height, $crop_width, $crop_height); $this->_info['width'] = $crop_width; $this->_info['height'] = $crop_height; imagedestroy($this->_handler); $this->_handler = $new; } return $this; }
Обрезание изображения @param int $left Левая граница @param int $top Верхняя граница @param int $right Правая граница @param int $bottom Нижняя граница @param bool $do Признак, выполнять трансформацию (true) или отложить до результата (пути на файл) @return $this
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/utils/Transform.php#L274-L303
Boolive/Core
utils/Transform.php
Transform.rotate
function rotate($angle, $do = false) { $angle = min(max(floatval($angle), -360), 360); if (!$do){ $this->_transforms[] = array('rotate', array($angle, true)); $this->_transforms_str.='rotate('.$angle.')'; }else{ $rgba = array(255,255,255,0); $handler = $this->handler(); $bg_color = imagecolorallocatealpha($handler, $rgba[0], $rgba[1], $rgba[2], $rgba[3]); $new = imagerotate($handler, $angle, $bg_color); imagesavealpha($new, true); imagealphablending($new, true); $this->_info['width'] = imagesx($new); $this->_info['height'] = imagesy($new); imagedestroy($this->_handler); $this->_handler = $new; } return $this; }
php
function rotate($angle, $do = false) { $angle = min(max(floatval($angle), -360), 360); if (!$do){ $this->_transforms[] = array('rotate', array($angle, true)); $this->_transforms_str.='rotate('.$angle.')'; }else{ $rgba = array(255,255,255,0); $handler = $this->handler(); $bg_color = imagecolorallocatealpha($handler, $rgba[0], $rgba[1], $rgba[2], $rgba[3]); $new = imagerotate($handler, $angle, $bg_color); imagesavealpha($new, true); imagealphablending($new, true); $this->_info['width'] = imagesx($new); $this->_info['height'] = imagesy($new); imagedestroy($this->_handler); $this->_handler = $new; } return $this; }
Поворот изображения @param float $angle Угол поворота от -360 до 360 @param bool $do Признак, выполнять трансформацию (true) или отложить до результата (пути на файл) @return $this
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/utils/Transform.php#L311-L329
Boolive/Core
utils/Transform.php
Transform.flip
function flip($dir = self::FLIP_X, $do = false) { $dir = intval($dir); if (!$do){ $this->_transforms[] = array('flip', array($dir, true)); $this->_transforms_str.='flip('.$dir.')'; }else{ $new = imagecreatetruecolor($w = $this->width(), $h = $this->height()); $src = $this->handler(); imagealphablending($new, false); imagesavealpha($new, true); switch ($dir) { case self::FLIP_Y: for ($i = 0; $i < $h; $i++) imagecopy($new, $src, 0, $i, 0, $h - $i - 1, $w, 1); break; default: for ($i = 0; $i < $w; $i++) imagecopy($new, $src, $i, 0, $w - $i - 1, 0, 1, $h); } imagedestroy($this->_handler); $this->_handler = $new; } return $this; }
php
function flip($dir = self::FLIP_X, $do = false) { $dir = intval($dir); if (!$do){ $this->_transforms[] = array('flip', array($dir, true)); $this->_transforms_str.='flip('.$dir.')'; }else{ $new = imagecreatetruecolor($w = $this->width(), $h = $this->height()); $src = $this->handler(); imagealphablending($new, false); imagesavealpha($new, true); switch ($dir) { case self::FLIP_Y: for ($i = 0; $i < $h; $i++) imagecopy($new, $src, 0, $i, 0, $h - $i - 1, $w, 1); break; default: for ($i = 0; $i < $w; $i++) imagecopy($new, $src, $i, 0, $w - $i - 1, 0, 1, $h); } imagedestroy($this->_handler); $this->_handler = $new; } return $this; }
Отражение изображения @param int $dir Направление отражения. Задаётся константами Transform::FLIP_* @param bool $do Признак, выполнять трансформацию (true) или отложить до результата (пути на файл) @return $this
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/utils/Transform.php#L337-L358
Boolive/Core
utils/Transform.php
Transform.gray
function gray($do = false) { if (!$do){ $this->_transforms[] = array('gray', array(true)); $this->_transforms_str.='gray()'; }else{ imagefilter($this->handler(), IMG_FILTER_GRAYSCALE); } return $this; }
php
function gray($do = false) { if (!$do){ $this->_transforms[] = array('gray', array(true)); $this->_transforms_str.='gray()'; }else{ imagefilter($this->handler(), IMG_FILTER_GRAYSCALE); } return $this; }
Преобразование в серые тона @param bool $do Признак, выполнять трансформацию (true) или отложить до результата (пути на файл) @return $this
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/utils/Transform.php#L365-L374
Boolive/Core
utils/Transform.php
Transform.quality
function quality($percent) { $this->info(); $this->_info['quality'] = intval($percent); if ($percent!=100){ $this->_transforms_str.='quality('.$this->_info['quality'].')'; } return $this; }
php
function quality($percent) { $this->info(); $this->_info['quality'] = intval($percent); if ($percent!=100){ $this->_transforms_str.='quality('.$this->_info['quality'].')'; } return $this; }
Качество изображения для jpg и png @param int $percent от 0 до 100 @return $this
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/utils/Transform.php#L381-L389
Boolive/Core
utils/Transform.php
Transform.convert
function convert($type) { if (in_array($type, array('gif','png','jpg'))){ $this->_transforms_str.='convert('.$type.')'; $this->_convert = $type; } return $this; }
php
function convert($type) { if (in_array($type, array('gif','png','jpg'))){ $this->_transforms_str.='convert('.$type.')'; $this->_convert = $type; } return $this; }
Смена расширения @param string $type Новое расширение (gif, png, jpg) @return $this
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/utils/Transform.php#L396-L403
Boolive/Core
utils/Transform.php
Transform.file
function file($transformed = true, $remake = false) { if ($transformed && !empty($this->_transforms_str)){ $pos = mb_strrpos($this->file, '.'); if ($pos === false){ $names = [null, $this->file]; }else{ $names = [mb_substr($this->file, 0, $pos, 'UTF-8'), mb_substr($this->file, $pos+1, null, 'UTF-8')]; } if (empty($this->_convert)) $this->_convert = $this->ext(); $file = $names[0].'.'.$this->_transforms_str.'.'.$this->_convert; $root_file = $this->getDir().'/'.$names[0].'.'.$this->_transforms_str.'.'.$this->_convert; if ($remake && is_file($root_file)){ unlink($root_file); } if (!is_file($root_file)){ foreach ($this->_transforms as $trans){ call_user_func_array(array($this, $trans[0]), $trans[1]); } $this->_info['width'] = @imagesx($this->_handler); $this->_info['height'] = @imagesy($this->_handler); @imageinterlace($this->_handler, true); switch ($this->_convert) { case 'gif': $result = @imagegif($this->_handler, $root_file); break; case 'jpg': $result = @imagejpeg($this->_handler, $root_file, round($this->_info['quality'])); break; case 'png': $result = @imagepng($this->_handler, $root_file, round(9 * $this->_info['quality'] / 100)); break; default: throw new \Exception('Не поддерживаем тип файла-изображения "'.$this->_convert.'"'); } if (!$result) { throw new \Exception('Не удалось сохранить изображение: '.$root_file); } } }else{ $file = $this->file; } return '/'.$file; }
php
function file($transformed = true, $remake = false) { if ($transformed && !empty($this->_transforms_str)){ $pos = mb_strrpos($this->file, '.'); if ($pos === false){ $names = [null, $this->file]; }else{ $names = [mb_substr($this->file, 0, $pos, 'UTF-8'), mb_substr($this->file, $pos+1, null, 'UTF-8')]; } if (empty($this->_convert)) $this->_convert = $this->ext(); $file = $names[0].'.'.$this->_transforms_str.'.'.$this->_convert; $root_file = $this->getDir().'/'.$names[0].'.'.$this->_transforms_str.'.'.$this->_convert; if ($remake && is_file($root_file)){ unlink($root_file); } if (!is_file($root_file)){ foreach ($this->_transforms as $trans){ call_user_func_array(array($this, $trans[0]), $trans[1]); } $this->_info['width'] = @imagesx($this->_handler); $this->_info['height'] = @imagesy($this->_handler); @imageinterlace($this->_handler, true); switch ($this->_convert) { case 'gif': $result = @imagegif($this->_handler, $root_file); break; case 'jpg': $result = @imagejpeg($this->_handler, $root_file, round($this->_info['quality'])); break; case 'png': $result = @imagepng($this->_handler, $root_file, round(9 * $this->_info['quality'] / 100)); break; default: throw new \Exception('Не поддерживаем тип файла-изображения "'.$this->_convert.'"'); } if (!$result) { throw new \Exception('Не удалось сохранить изображение: '.$root_file); } } }else{ $file = $this->file; } return '/'.$file; }
Файл, ассоциированный с объектом. Если были выполнены трансформации, то возвращается путь на трансформированное изображение
https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/utils/Transform.php#L409-L454
ellipsephp/container-reflection
src/AbstractReflectionContainer.php
AbstractReflectionContainer.isAutoWirable
private function isAutoWirable($id): bool { if (is_string($id) && class_exists($id)) { if (count($this->interfaces) > 0) { return (bool) array_intersect($this->interfaces, class_implements($id)); } return true; } return false; }
php
private function isAutoWirable($id): bool { if (is_string($id) && class_exists($id)) { if (count($this->interfaces) > 0) { return (bool) array_intersect($this->interfaces, class_implements($id)); } return true; } return false; }
Return whether the given id is an auto wirable class. @param $id @return bool
https://github.com/ellipsephp/container-reflection/blob/bd35a26e0fc924788f54b560d4a2d72ecf9a2be9/src/AbstractReflectionContainer.php#L99-L114
ellipsephp/container-reflection
src/AbstractReflectionContainer.php
AbstractReflectionContainer.make
private function make(string $class) { if (! array_key_exists($class, $this->instances)) { try { return $this->instances[$class] = ($this->factory)($class)->value($this); } catch (ResolvingExceptionInterface $e) { throw new ReflectionContainerException($class, $e); } } return $this->instances[$class]; }
php
private function make(string $class) { if (! array_key_exists($class, $this->instances)) { try { return $this->instances[$class] = ($this->factory)($class)->value($this); } catch (ResolvingExceptionInterface $e) { throw new ReflectionContainerException($class, $e); } } return $this->instances[$class]; }
Return an instance of the given class name. Cache the created instance so the same one is returned on multiple calls. @param string $class @return mixed @throws \Ellipse\Container\Exceptions\ReflectionContainerException
https://github.com/ellipsephp/container-reflection/blob/bd35a26e0fc924788f54b560d4a2d72ecf9a2be9/src/AbstractReflectionContainer.php#L124-L143
4devs/serializer
Accessor/GetSet.php
GetSet.getValue
public function getValue($object, array $options = [], array $context = []) { $data = null; if ($options['getter']) { $data = $object->{$options['getter']}(); } return $data; }
php
public function getValue($object, array $options = [], array $context = []) { $data = null; if ($options['getter']) { $data = $object->{$options['getter']}(); } return $data; }
{@inheritdoc}
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Accessor/GetSet.php#L22-L30
4devs/serializer
Accessor/GetSet.php
GetSet.configureOptions
public function configureOptions(OptionsResolver $resolver) { $resolver ->setDefined(['getter', 'setter', 'property']) ->setDefaults([ 'getter' => function (Options $options) { return $options['property'] ? 'get'.ucfirst($options['property']) : null; }, 'setter' => function (Options $options) { return $options['property'] ? 'set'.ucfirst($options['property']) : null; }, 'property' => null, ]) ->setAllowedTypes('property', ['string', 'null']) ->setAllowedTypes('getter', ['string', 'null']) ->setAllowedTypes('setter', ['string', 'null']); }
php
public function configureOptions(OptionsResolver $resolver) { $resolver ->setDefined(['getter', 'setter', 'property']) ->setDefaults([ 'getter' => function (Options $options) { return $options['property'] ? 'get'.ucfirst($options['property']) : null; }, 'setter' => function (Options $options) { return $options['property'] ? 'set'.ucfirst($options['property']) : null; }, 'property' => null, ]) ->setAllowedTypes('property', ['string', 'null']) ->setAllowedTypes('getter', ['string', 'null']) ->setAllowedTypes('setter', ['string', 'null']); }
{@inheritdoc}
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Accessor/GetSet.php#L45-L61
fnayou/instapush-php
src/Http/AbstractHttpClientConfigurator.php
AbstractHttpClientConfigurator.appendPlugin
public function appendPlugin(Plugin ...$plugins) { foreach ($plugins as $plugin) { $this->appendPlugins[] = $plugin; } return $this; }
php
public function appendPlugin(Plugin ...$plugins) { foreach ($plugins as $plugin) { $this->appendPlugins[] = $plugin; } return $this; }
@param \Http\Client\Common\Plugin ...$plugins @return $this
https://github.com/fnayou/instapush-php/blob/fa7bd9091cf4dee767449412dc10911f4afbdf24/src/Http/AbstractHttpClientConfigurator.php#L107-L114
fnayou/instapush-php
src/Http/AbstractHttpClientConfigurator.php
AbstractHttpClientConfigurator.prependPlugin
public function prependPlugin(Plugin ...$plugins) { $plugins = \array_reverse($plugins); foreach ($plugins as $plugin) { \array_unshift($this->prependPlugins, $plugin); } return $this; }
php
public function prependPlugin(Plugin ...$plugins) { $plugins = \array_reverse($plugins); foreach ($plugins as $plugin) { \array_unshift($this->prependPlugins, $plugin); } return $this; }
@param \Http\Client\Common\Plugin ...$plugins @return $this
https://github.com/fnayou/instapush-php/blob/fa7bd9091cf4dee767449412dc10911f4afbdf24/src/Http/AbstractHttpClientConfigurator.php#L121-L130
upiksaleh/codeup-yihai
src/theming/Progress.php
Progress.run
public function run() { //BootstrapAsset::register($this->getView()); return implode("\n", [ Html::beginTag('div', $this->options), $this->renderProgress(), Html::endTag('div') ]) . "\n"; }
php
public function run() { //BootstrapAsset::register($this->getView()); return implode("\n", [ Html::beginTag('div', $this->options), $this->renderProgress(), Html::endTag('div') ]) . "\n"; }
Renders the widget.
https://github.com/upiksaleh/codeup-yihai/blob/98f3db37963157f8fa18c1637acc8d3877f6c982/src/theming/Progress.php#L106-L114
pmdevelopment/tool-bundle
Framework/Model/ChartJs/DataObject.php
DataObject.exportDataSets
public function exportDataSets($dataSetConfig = null) { $response = []; foreach ($this->getDataSets() as $set) { if ($set instanceof DataSet) { $response[] = $set->export($dataSetConfig); } else { $response[] = $set; } } return $response; }
php
public function exportDataSets($dataSetConfig = null) { $response = []; foreach ($this->getDataSets() as $set) { if ($set instanceof DataSet) { $response[] = $set->export($dataSetConfig); } else { $response[] = $set; } } return $response; }
Export Data Sets @param DataSetConfig|null $dataSetConfig @return array
https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Framework/Model/ChartJs/DataObject.php#L64-L77
Elephant418/Staq
src/Staq/Core/Data/Stack/Attribute/Relation/ManyToMany.php
ManyToMany.initBySetting
public function initBySetting($model, $setting) { parent::initBySetting($model, $setting); if (is_array($setting)) { if (!isset($setting['table'])) { throw new \Stack\Exception\MissingSetting('"table" missing for the ManyToMany relation.'); } if (!isset($setting['remote_attribute_name'])) { throw new \Stack\Exception\MissingSetting('"remote_attribute_name" missing for the ManyToMany relation.'); } $this->table = $setting['table']; $this->remoteAttributeName = $setting['remote_attribute_name']; } }
php
public function initBySetting($model, $setting) { parent::initBySetting($model, $setting); if (is_array($setting)) { if (!isset($setting['table'])) { throw new \Stack\Exception\MissingSetting('"table" missing for the ManyToMany relation.'); } if (!isset($setting['remote_attribute_name'])) { throw new \Stack\Exception\MissingSetting('"remote_attribute_name" missing for the ManyToMany relation.'); } $this->table = $setting['table']; $this->remoteAttributeName = $setting['remote_attribute_name']; } }
/* CONSTRUCTOR ***********************************************************************
https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Core/Data/Stack/Attribute/Relation/ManyToMany.php#L20-L33
Elephant418/Staq
src/Staq/Core/Data/Stack/Attribute/Relation/ManyToMany.php
ManyToMany.reload
public function reload() { $class = $this->getRemoteClass(); $this->remoteModels = (new $class)->entity->fetchByRelatedThroughTable($this->table, $this->remoteAttributeName, $this->relatedAttributeName, $this->model, $this->filterList); }
php
public function reload() { $class = $this->getRemoteClass(); $this->remoteModels = (new $class)->entity->fetchByRelatedThroughTable($this->table, $this->remoteAttributeName, $this->relatedAttributeName, $this->model, $this->filterList); }
/* PUBLIC USER METHODS ***********************************************************************
https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Core/Data/Stack/Attribute/Relation/ManyToMany.php#L38-L42
Elephant418/Staq
src/Staq/Core/Data/Stack/Attribute/Relation/ManyToMany.php
ManyToMany.saveHandler
public function saveHandler() { if ($this->changed) { $class = $this->getRemoteClass(); (new $class)->entity->updateRelatedThroughTable($this->table, $this->remoteAttributeName, $this->relatedAttributeName, $this->getIds(), $this->model, $this->filterList); } }
php
public function saveHandler() { if ($this->changed) { $class = $this->getRemoteClass(); (new $class)->entity->updateRelatedThroughTable($this->table, $this->remoteAttributeName, $this->relatedAttributeName, $this->getIds(), $this->model, $this->filterList); } }
/* HANDLER METHODS ***********************************************************************
https://github.com/Elephant418/Staq/blob/b96110eb069a2b3fd992d3e56327a54a308b68b2/src/Staq/Core/Data/Stack/Attribute/Relation/ManyToMany.php#L55-L61
buse974/Dal
src/Dal/Db/Sql/Sql.php
Sql.select
public function select($table = null) { if ($this->table !== null && $table !== null) { throw new InvalidArgumentException(sprintf( 'This Sql object is intended to work with only the table "%s" provided at construction time.', $this->table )); } return new \Dal\Db\Sql\Select(($table) ?: $this->table); }
php
public function select($table = null) { if ($this->table !== null && $table !== null) { throw new InvalidArgumentException(sprintf( 'This Sql object is intended to work with only the table "%s" provided at construction time.', $this->table )); } return new \Dal\Db\Sql\Select(($table) ?: $this->table); }
(non-PHPdoc). @see \Zend\Db\Sql\Sql::select()
https://github.com/buse974/Dal/blob/faeac9e260c5e675bc7ed1fcea77c7ba251bf8ab/src/Dal/Db/Sql/Sql.php#L15-L25
Synapse-Cmf/synapse-cmf
src/Synapse/Cmf/Bundle/SynapseCmfBundle.php
SynapseCmfBundle.build
public function build(ContainerBuilder $container) { $loader = new YamlFileLoader( $container, new FileLocator(__DIR__.'/Resources/config') ); $loader->load('config.yml'); $container->addCompilerPass( $this->getContainerExtension(), PassConfig::TYPE_REMOVE ); }
php
public function build(ContainerBuilder $container) { $loader = new YamlFileLoader( $container, new FileLocator(__DIR__.'/Resources/config') ); $loader->load('config.yml'); $container->addCompilerPass( $this->getContainerExtension(), PassConfig::TYPE_REMOVE ); }
{@inheritdoc}
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Bundle/SynapseCmfBundle.php#L20-L32
Tuna-CMS/tuna-bundle
src/Tuna/Bundle/FileBundle/Controller/DefaultController.php
DefaultController.getErrorResponse
private function getErrorResponse(FormInterface $form) { $errors = $form->getErrors(); $errorCollection = []; foreach ($errors as $error) { $errorCollection[] = $error->getMessage(); } return new JsonResponse([ 'messages' => $errorCollection, ], 400); }
php
private function getErrorResponse(FormInterface $form) { $errors = $form->getErrors(); $errorCollection = []; foreach ($errors as $error) { $errorCollection[] = $error->getMessage(); } return new JsonResponse([ 'messages' => $errorCollection, ], 400); }
@param FormInterface $form @return JsonResponse
https://github.com/Tuna-CMS/tuna-bundle/blob/1f999de44e14cbe9f992d46f2e5e74ddc117b04c/src/Tuna/Bundle/FileBundle/Controller/DefaultController.php#L52-L64
Tuna-CMS/tuna-bundle
src/Tuna/Bundle/FileBundle/Controller/DefaultController.php
DefaultController.getFileInfo
private function getFileInfo(UploadedFile $file) { $fileManager = $this->get('tuna_cms_file.manager.file_manager'); $filename = $fileManager->generateTmpFilename($file); return [ 'path' => $filename, 'mimeType' => $file->getMimeType(), 'originalName' => $file->getClientOriginalName(), ]; }
php
private function getFileInfo(UploadedFile $file) { $fileManager = $this->get('tuna_cms_file.manager.file_manager'); $filename = $fileManager->generateTmpFilename($file); return [ 'path' => $filename, 'mimeType' => $file->getMimeType(), 'originalName' => $file->getClientOriginalName(), ]; }
@param UploadedFile $file @return array
https://github.com/Tuna-CMS/tuna-bundle/blob/1f999de44e14cbe9f992d46f2e5e74ddc117b04c/src/Tuna/Bundle/FileBundle/Controller/DefaultController.php#L71-L81
rackberg/para
src/Command/InstallPluginCommand.php
InstallPluginCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $pluginName = $input->getArgument('name'); $version = $input->getArgument('version'); try { $installOutput = $this->pluginManager->installPlugin($pluginName, $version); if ($output->isDebug()) { $output->write($installOutput); } $output->writeln( sprintf( '<info>The plugin "%s" version "%s" has been installed successfully.</info>', $pluginName, $version ) ); } catch (PluginAlreadyInstalledException $e) { $output->writeln('<comment>' . $e->getMessage() . '</comment>'); } catch (PluginNotFoundException $e) { $output->writeln('<error>' . $e->getMessage() . '</error>'); } }
php
protected function execute(InputInterface $input, OutputInterface $output) { $pluginName = $input->getArgument('name'); $version = $input->getArgument('version'); try { $installOutput = $this->pluginManager->installPlugin($pluginName, $version); if ($output->isDebug()) { $output->write($installOutput); } $output->writeln( sprintf( '<info>The plugin "%s" version "%s" has been installed successfully.</info>', $pluginName, $version ) ); } catch (PluginAlreadyInstalledException $e) { $output->writeln('<comment>' . $e->getMessage() . '</comment>'); } catch (PluginNotFoundException $e) { $output->writeln('<error>' . $e->getMessage() . '</error>'); } }
{@inheritdoc}
https://github.com/rackberg/para/blob/e0ef1356ed2979670eb7c670d88921406cade46e/src/Command/InstallPluginCommand.php#L61-L84
crisu83/yii-consoletools
commands/PermissionsCommand.php
PermissionsCommand.run
public function run($args) { foreach ($this->permissions as $dir => $config) { $path = $this->basePath . '/' . $dir; if (file_exists($path)) { try { if (isset($config['user'])) { $this->changeOwner($path, $config['user']); } if (isset($config['group'])) { $this->changeGroup($path, $config['group']); } if (isset($config['mode'])) { $this->changeMode($path, $config['mode']); } } catch(CException $e) { echo $this->formatError($e->getMessage())."\n"; } } else { echo sprintf("Failed to change permissions for %s. File does not exist!\n", $path); } } echo "Permissions successfully changed.\n"; return 0; }
php
public function run($args) { foreach ($this->permissions as $dir => $config) { $path = $this->basePath . '/' . $dir; if (file_exists($path)) { try { if (isset($config['user'])) { $this->changeOwner($path, $config['user']); } if (isset($config['group'])) { $this->changeGroup($path, $config['group']); } if (isset($config['mode'])) { $this->changeMode($path, $config['mode']); } } catch(CException $e) { echo $this->formatError($e->getMessage())."\n"; } } else { echo sprintf("Failed to change permissions for %s. File does not exist!\n", $path); } } echo "Permissions successfully changed.\n"; return 0; }
Runs the command. @param array $args the command-line arguments. @return integer the return code.
https://github.com/crisu83/yii-consoletools/blob/53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc/commands/PermissionsCommand.php#L63-L87
crisu83/yii-consoletools
commands/PermissionsCommand.php
PermissionsCommand.changeOwner
protected function changeOwner($path, $newOwner) { $ownerUid = fileowner($path); $ownerData = posix_getpwuid($ownerUid); $oldOwner = $ownerData['name']; if ($oldOwner !== $this->user) { if(!@chown($path, $newOwner)) { throw new CException(sprintf('Unable to change owner for %s, permission denied', $path)); } echo sprintf("Changing owner for %s (%s => %s)... ", $path, $oldOwner, $newOwner); echo "done\n"; } }
php
protected function changeOwner($path, $newOwner) { $ownerUid = fileowner($path); $ownerData = posix_getpwuid($ownerUid); $oldOwner = $ownerData['name']; if ($oldOwner !== $this->user) { if(!@chown($path, $newOwner)) { throw new CException(sprintf('Unable to change owner for %s, permission denied', $path)); } echo sprintf("Changing owner for %s (%s => %s)... ", $path, $oldOwner, $newOwner); echo "done\n"; } }
Changes the owner for a directory. @param string $path the directory path. @param string $newOwner the name of the new owner.
https://github.com/crisu83/yii-consoletools/blob/53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc/commands/PermissionsCommand.php#L94-L106
crisu83/yii-consoletools
commands/PermissionsCommand.php
PermissionsCommand.changeGroup
protected function changeGroup($path, $newGroup) { $groupGid = filegroup($path); $groupData = posix_getgrgid($groupGid); $oldGroup = $groupData['name']; if ($oldGroup !== $newGroup) { if(!@chgrp($path, $newGroup)) { throw new CException(sprintf('Unable to change group for %s, permission denied', $path)); } echo sprintf("Changing group for %s (%s => %s)... ", $path, $oldGroup, $newGroup); echo "done\n"; } }
php
protected function changeGroup($path, $newGroup) { $groupGid = filegroup($path); $groupData = posix_getgrgid($groupGid); $oldGroup = $groupData['name']; if ($oldGroup !== $newGroup) { if(!@chgrp($path, $newGroup)) { throw new CException(sprintf('Unable to change group for %s, permission denied', $path)); } echo sprintf("Changing group for %s (%s => %s)... ", $path, $oldGroup, $newGroup); echo "done\n"; } }
Changes the group for a directory. @param string $path the directory path. @param string $newGroup the name of the new group.
https://github.com/crisu83/yii-consoletools/blob/53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc/commands/PermissionsCommand.php#L113-L125
crisu83/yii-consoletools
commands/PermissionsCommand.php
PermissionsCommand.changeMode
protected function changeMode($path, $mode) { $oldPermission = substr(sprintf('%o', fileperms($path)), -4); $newPermission = sprintf('%04o', $mode); if ($oldPermission !== $newPermission) { if(!@chmod($path, $mode)) { throw new CException (sprintf("Unable to change mode for %s, permission denied", $path)); } echo sprintf("Changing mode for %s (%s => %s)... ", $path, $oldPermission, $newPermission); echo "done\n"; } }
php
protected function changeMode($path, $mode) { $oldPermission = substr(sprintf('%o', fileperms($path)), -4); $newPermission = sprintf('%04o', $mode); if ($oldPermission !== $newPermission) { if(!@chmod($path, $mode)) { throw new CException (sprintf("Unable to change mode for %s, permission denied", $path)); } echo sprintf("Changing mode for %s (%s => %s)... ", $path, $oldPermission, $newPermission); echo "done\n"; } }
Changes the mode for a directory. @param string $path the directory path. @param integer $mode the mode.
https://github.com/crisu83/yii-consoletools/blob/53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc/commands/PermissionsCommand.php#L132-L143
IftekherSunny/Planet-Framework
src/Sun/Http/Redirect.php
Redirect.to
public function to($url, array $values = []) { $url = $this->urlGenerator->getBaseUri() . $url; $this->session->create('planet_oldInput', []); if (count($values)) { foreach ($values as $key => $value) { $this->with($key, $value); } } header('location: ' . $url); if($this->hasData) exit(); }
php
public function to($url, array $values = []) { $url = $this->urlGenerator->getBaseUri() . $url; $this->session->create('planet_oldInput', []); if (count($values)) { foreach ($values as $key => $value) { $this->with($key, $value); } } header('location: ' . $url); if($this->hasData) exit(); }
To redirect @param string $url @param array $values
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Http/Redirect.php#L47-L62
IftekherSunny/Planet-Framework
src/Sun/Http/Redirect.php
Redirect.with
public function with($key, $value) { $this->hasData = true; $this->session->create($key, $value); return $this; }
php
public function with($key, $value) { $this->hasData = true; $this->session->create($key, $value); return $this; }
To store data in a session @param string $key @param mixed $value @return $this
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Http/Redirect.php#L72-L79
IftekherSunny/Planet-Framework
src/Sun/Http/Redirect.php
Redirect.backWith
public function backWith($key, $value) { $this->with($key, $value); $url = $this->session->get('previous_uri'); header('location: ' . $url); exit(); }
php
public function backWith($key, $value) { $this->with($key, $value); $url = $this->session->get('previous_uri'); header('location: ' . $url); exit(); }
To redirect back with value @param string $key @param mixed $value
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Http/Redirect.php#L97-L105
pilipinews/common
src/Converters/LinkConverter.php
LinkConverter.convert
public function convert(ElementInterface $element) { $text = trim($element->getValue(), "\t\n\r\0\x0B"); $href = $element->getAttribute('href'); $markdown = $text . ' (' . $href . ')'; $autolink = $this->isValidAutolink((string) $href); $href === $text && $autolink && $markdown = $href; return $markdown; }
php
public function convert(ElementInterface $element) { $text = trim($element->getValue(), "\t\n\r\0\x0B"); $href = $element->getAttribute('href'); $markdown = $text . ' (' . $href . ')'; $autolink = $this->isValidAutolink((string) $href); $href === $text && $autolink && $markdown = $href; return $markdown; }
Converts the specified element into a parsed string. @param \League\HTMLToMarkdown\ElementInterface $element @return string
https://github.com/pilipinews/common/blob/a39f16e935b3b8e97b54b6e9348a1deab2d0a2a0/src/Converters/LinkConverter.php#L22-L35
matryoshka-model/matryoshka
library/Object/AbstractCollection.php
AbstractCollection.offsetSet
public function offsetSet($key, $value) { $this->validateValue($value); return parent::offsetSet($key, $value); }
php
public function offsetSet($key, $value) { $this->validateValue($value); return parent::offsetSet($key, $value); }
{@inheritdoc} @throws Exception\InvalidArgumentException
https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/Object/AbstractCollection.php#L83-L87
matryoshka-model/matryoshka
library/Object/AbstractCollection.php
AbstractCollection.exchangeArray
public function exchangeArray($data) { $oldData = parent::exchangeArray($data); try { $this->validateData($this->storage); } catch (\Exception $e) { $this->storage = $oldData; throw $e; } return $oldData; }
php
public function exchangeArray($data) { $oldData = parent::exchangeArray($data); try { $this->validateData($this->storage); } catch (\Exception $e) { $this->storage = $oldData; throw $e; } return $oldData; }
{@inheritdoc}
https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/Object/AbstractCollection.php#L109-L119
akumar2-velsof/guzzlehttp
src/RingBridge.php
RingBridge.createRingRequest
public static function createRingRequest(RequestInterface $request) { $options = $request->getConfig()->toArray(); $url = $request->getUrl(); // No need to calculate the query string twice (in URL and query). $qs = ($pos = strpos($url, '?')) ? substr($url, $pos + 1) : null; return [ 'scheme' => $request->getScheme(), 'http_method' => $request->getMethod(), 'url' => $url, 'uri' => $request->getPath(), 'headers' => $request->getHeaders(), 'body' => $request->getBody(), 'version' => $request->getProtocolVersion(), 'client' => $options, 'query_string' => $qs, 'future' => isset($options['future']) ? $options['future'] : false ]; }
php
public static function createRingRequest(RequestInterface $request) { $options = $request->getConfig()->toArray(); $url = $request->getUrl(); // No need to calculate the query string twice (in URL and query). $qs = ($pos = strpos($url, '?')) ? substr($url, $pos + 1) : null; return [ 'scheme' => $request->getScheme(), 'http_method' => $request->getMethod(), 'url' => $url, 'uri' => $request->getPath(), 'headers' => $request->getHeaders(), 'body' => $request->getBody(), 'version' => $request->getProtocolVersion(), 'client' => $options, 'query_string' => $qs, 'future' => isset($options['future']) ? $options['future'] : false ]; }
Creates a Ring request from a request object. This function does not hook up the "then" and "progress" events that would be required for actually sending a Guzzle request through a RingPHP handler. @param RequestInterface $request Request to convert. @return array Converted Guzzle Ring request.
https://github.com/akumar2-velsof/guzzlehttp/blob/9588a489c52b27e2d4047f146ddacffc3e111b7e/src/RingBridge.php#L28-L47
akumar2-velsof/guzzlehttp
src/RingBridge.php
RingBridge.prepareRingRequest
public static function prepareRingRequest(Transaction $trans) { // Clear out the transaction state when initiating. $trans->exception = null; $request = self::createRingRequest($trans->request); // Emit progress events if any progress listeners are registered. if ($trans->request->getEmitter()->hasListeners('progress')) { $emitter = $trans->request->getEmitter(); $request['client']['progress'] = function ($a, $b, $c, $d) use ($trans, $emitter) { $emitter->emit('progress', new ProgressEvent($trans, $a, $b, $c, $d)); }; } return $request; }
php
public static function prepareRingRequest(Transaction $trans) { // Clear out the transaction state when initiating. $trans->exception = null; $request = self::createRingRequest($trans->request); // Emit progress events if any progress listeners are registered. if ($trans->request->getEmitter()->hasListeners('progress')) { $emitter = $trans->request->getEmitter(); $request['client']['progress'] = function ($a, $b, $c, $d) use ($trans, $emitter) { $emitter->emit('progress', new ProgressEvent($trans, $a, $b, $c, $d)); }; } return $request; }
Creates a Ring request from a request object AND prepares the callbacks. @param Transaction $trans Transaction to update. @return array Converted Guzzle Ring request.
https://github.com/akumar2-velsof/guzzlehttp/blob/9588a489c52b27e2d4047f146ddacffc3e111b7e/src/RingBridge.php#L56-L71
akumar2-velsof/guzzlehttp
src/RingBridge.php
RingBridge.completeRingResponse
public static function completeRingResponse( Transaction $trans, array $response, MessageFactoryInterface $messageFactory ) { $trans->state = 'complete'; $trans->transferInfo = isset($response['transfer_stats']) ? $response['transfer_stats'] : []; if (!empty($response['status'])) { $options = []; if (isset($response['version'])) { $options['protocol_version'] = $response['version']; } if (isset($response['reason'])) { $options['reason_phrase'] = $response['reason']; } $trans->response = $messageFactory->createResponse( $response['status'], isset($response['headers']) ? $response['headers'] : [], isset($response['body']) ? $response['body'] : null, $options ); if (isset($response['effective_url'])) { $trans->response->setEffectiveUrl($response['effective_url']); } } elseif (empty($response['error'])) { // When nothing was returned, then we need to add an error. $response['error'] = self::getNoRingResponseException($trans->request); } if (isset($response['error'])) { $trans->state = 'error'; $trans->exception = $response['error']; } }
php
public static function completeRingResponse( Transaction $trans, array $response, MessageFactoryInterface $messageFactory ) { $trans->state = 'complete'; $trans->transferInfo = isset($response['transfer_stats']) ? $response['transfer_stats'] : []; if (!empty($response['status'])) { $options = []; if (isset($response['version'])) { $options['protocol_version'] = $response['version']; } if (isset($response['reason'])) { $options['reason_phrase'] = $response['reason']; } $trans->response = $messageFactory->createResponse( $response['status'], isset($response['headers']) ? $response['headers'] : [], isset($response['body']) ? $response['body'] : null, $options ); if (isset($response['effective_url'])) { $trans->response->setEffectiveUrl($response['effective_url']); } } elseif (empty($response['error'])) { // When nothing was returned, then we need to add an error. $response['error'] = self::getNoRingResponseException($trans->request); } if (isset($response['error'])) { $trans->state = 'error'; $trans->exception = $response['error']; } }
Handles the process of processing a response received from a ring handler. The created response is added to the transaction, and the transaction stat is set appropriately. @param Transaction $trans Owns request and response. @param array $response Ring response array @param MessageFactoryInterface $messageFactory Creates response objects.
https://github.com/akumar2-velsof/guzzlehttp/blob/9588a489c52b27e2d4047f146ddacffc3e111b7e/src/RingBridge.php#L82-L117