Commit file deletions with Laravel package GrahamCampbell/Laravel-GitHub - laravel

Using GrahamCampbell/Laravel-GitHub my Laravel app can commit files like this:
public function commitFiles(string $github_nickname, string $repo_name, string $branch, string $commit_message, array $files) {
$master_branch = $this->github_client->repo()->branches($github_nickname, $repo_name, $branch);
$commit_parent = $master_branch["commit"]["sha"];
$base_tree = $master_branch["commit"]["commit"]["tree"]["sha"];
$commit_tree = array();
foreach ($files as $file) {
$file_blob = [
"path" => $file["path"],
"mode" => "100644",
"type" => "file",
"content" => $file["content"],
];
array_push($commit_tree, $file_blob);
}
$new_commit_tree_response = $this->github_client->git()->trees()->create($github_nickname, $repo_name, [
"base_tree" => $base_tree,
"tree" => $commit_tree
]);
// TODO verify commit with GPG
$new_commit_response = $this->github_client->git()->commits()->create($github_nickname, $repo_name, [
"message" => $commit_message,
"parents" => [$commit_parent],
"tree" => $new_commit_tree_response["sha"],
]);
$this->github_client->git()->references()->update($github_nickname, $repo_name, "heads/".$branch, [
"sha" => $new_commit_response["sha"],
"force" => false,
]);
return true;
}
But how can I delete files? I have not found any applicable documentation and have a really hard time figuring this out.

Here is a way to remove one file:
public function deleteFile($github_nickname, $repo_name, $path, $commitMessage)
{
$committer = array('name' => 'SomeName', 'email' => 'some#email.com');
$oldFile = $this->github_client->api('repo')->contents()->show($github_nickname, $repo_name, $path, 'master');
$this->github_client->api('repo')->contents()->rm($github_nickname, $repo_name, $path, $commitMessage, $oldFile['sha'], 'master', $committer);
}

Related

Failed asserting that a row in the table student.sections matches the attributes

Hello im new to PHPUnit with minimum knowledge in laravel.
Im trying to test this method that mass create student section
public function setStudentsSection(Request $request)
{
$enrollments = Enrollment::whereIn('student_id', $request->students)->where('session_id', $request->session_id)->get();
$program_section = ProgramSection::withCount('students')->find($request->program_section_id);
if(($program_section->students_count + count($enrollments)) <= $program_section->max_students) {
foreach($enrollments as $enrollment) {
$response = StudentSection::create([
'student_id' => $enrollment->student_id,
'enrollment_id' => $enrollment->id,
'section_id' => $request->program_section_id,
'created_at' => Carbon::now()
]);
return $response;
}
}
return response()->json(['errors' => ['message' => 'Selected Section is full.']], 405);
}
UPDATE
Here's the test case. Im trying to match the method that i've modified with my test, but im failing to do so.
public function testCanMassAssignSection()
{
$sectioning_data = $this->setMassSectioning(10);
$this->json('POST', 'api/enrollments/set-students-section', $sectioning_data['data'])
->assertStatus(201);
$student_section_data = ['student_id' => $sectioning_data['student_ids'], 'section_id' => $sectioning_data['program_section']->id];
$this->assertDatabaseHas('student.sections', $student_section_data);
}
private function setMassSectioning($max_students)
{
$session = Session::factory()->create();
$program_section = ProgramSection::factory()->create(['session_id' => $session->id, 'max_students' => $max_students]);
$enrollments = Enrollment::factory(['session_id' => $session->id])->count(3)->create();
$student_ids = array();
foreach($enrollments as $enrollment) {
array_push($student_ids, $enrollment->student_id);
}
return [
'data' => ['program_section_id' => $program_section->id, 'session_id' => $session->id, 'students' => $student_ids],
'student_ids' => $enrollment->student_id,
'program_section' => $program_section
];
}
UPDATE
Here's the error the i get.
1) Test\Feature\EnrollmentTest::testCanMassAssignSection
Failed asserting that a row in the table [student.sections] matches the attributes {
"student_id": 2765,
"section_id": 1649
}.
Found: [
{
"id": 262,
"student_id": 2763,
"section_id": 1649,
"created_at": "2022-08-24 09:32:05",
"updated_at": "2022-08-24 09:32:05",
"enrollment_id": 1740
}
].
Still can't make it to match. I do not know what im doing wrong.
Solve! I just create $student data and added to $enrollments now assert in database match. Although don't know what exactly is happening on the background.
I think when i added to enrollments variable the 'student_id' => $student->id it creates those 3 records.
private function setMassSectioning($max_students)
{
$session = Session::factory()->create();
$student = Student::factory()->create();
$program_section = ProgramSection::factory()->create(['session_id' => $session->id, 'max_students' => $max_students]);
$enrollments = Enrollment::factory(['session_id' => $session->id, 'student_id' => $student->id])->count(3)->create();
$student_ids = array();
foreach($enrollments as $enrollment) {
array_push($student_ids, $enrollment->student_id);
}
return [
'data' => ['program_section_id' => $program_section->id, 'session_id' => $session->id, 'students' => $student_ids],
'student_ids' => $enrollment->student_id,
'program_section' => $program_section
];
}

Map array values to collection of items

How would one do the following elegantly with laravel collections ?
Map the values of the $baseMap as keys to the collection.
The baseMap :
$baseMap = [
'name' => 'new_name',
'year' => 'new_year',
];
The collection :
$items = collect([
[
'name' => 'name1',
'year' => '1000',
'not_in_basemap' => 'foo'
],
[
'name' => 'name2',
'year' => '2000',
'not_in_basemap' => 'foo'
],
//...
]);
The end result :
$result =[
[
'new_name' => 'name1',
'new_year' => '1000',
],
[
'new_name'=> 'name2',
'new_year' => '2000',
],
];
I know how to do it in plain php , just wondering what a nice collection version would be. Thanks!
I tried to find collection methods, or php functions, but without success. Some dirty code that works with different keys from both sides (items and basemap).
$result = $items->map(function($item) use ($baseMap) {
$array = [];
foreach($baseMap as $oldKey => $newKey){
if(isset($item[$oldKey])){
$array[$newKey] = $item[$oldKey];
}
}
return $array;
});
$result = $result->toArray();
Thanks to #vivek_23 and #IndianCoding for giving me idea's I ended up with the following :
I made a small edit to make sure the mapping and the items keys lined up.
so you don't have to worry of misalignment and all in laravel collection !
$baseMap = collect($baseMap)->sortKeys();
$result = $items->map(function ($item) use ($baseMap) {
return $baseMap->values()
->combine(
collect($item)->sortKeys()->intersectByKeys($baseMap)
)
->all();
});
Use intersectByKeys to filter your baseMap keys with $items values.
$result = $items->map(function($item,$key) use ($baseMap){
return array_combine(array_values($baseMap),collect($item)->intersectByKeys($baseMap)->all());
});
dd($result);
Update:
In a pure collection way,
$baseMapCollect = collect($baseMap);
$result = $items->map(function($item,$key) use ($baseMapCollect){
return $baseMapCollect->values()->combine(collect($item)->intersectByKeys($baseMapCollect->all())->values())->all();
});
dd($result);
Here are my two cents, using map. Don't know how dynamic your collection should be, but knowing the keys I would do the following:
$baseMap = [
'name' => 'new_name',
'year' => 'new_year',
];
$items = collect([
[
'name' => 'name1',
'year' => '1000',
'not_in_basemap' => 'foo'
],
[
'name' => 'name2',
'year' => '2000',
'not_in_basemap' => 'foo'
],
])->map(function($item, $key) use ($baseMap) {
return [
$baseMap['name'] => $item['name'],
$baseMap['year'] => $item['year']
];
});

laravel save pdf no such file or directory

So I want to save a pdf file to a directory on my local server but it keeps saying that the directory does not exist.
So first of all where would you store PDF files that are not accessible to by externals (so not in the public folder).
So this is my code. The download works perfectly.
public function generatePDF()
{
$this->mailorder = Session::get('order');
$this->cart = Session::get('cart');
$data = [
'id' => $this->mailorder->id,
'client' => $this->mailorder->Contact,
'country' => $this->mailorder->country,
'city' => $this->mailorder->city,
'street' => $this->mailorder->street,
'postal' => $this->mailorder->postal,
'phone' => $this->mailorder->phone,
'email' => $this->mailorder->email,
'dateIn' => $this->mailorder->dateIn,
'dateOut' => $this->mailorder->dateOut,
'subtotal' => $this->mailorder->subtotal,
'tax' => $this->mailorder->tax,
'total' => $this->mailorder->total,
'cart' => $this->mailorder->cart,
'delivery' => $this->mailorder->delivery,
];
$path = "order_{$this->mailorder->id}_{$this->mailorder->Contact}";
$pdf = PDF::loadView('pdf.orderConfirmationPdf', $data)->save('storage/app/public/'.$path.'.pdf');
;
return $pdf->download(''.$path.'.pdf');
}
First of all, you should check if the directory exists with File facade. If it does not exist, you must make the directory.
if(!File::exists($directory_path)) {
File::makeDirectory($directory_path);
}
If the error still occurs, you must force it to make the directory:
if(!File::exists($directory_path)) {
File::makeDirectory($directory_path, $mode = 0755, true, true);
}
After that, you can save the file in that directory.
Second, if you don't want to save the file in the public directory. you must save it in storage.By simply call storage_path($file_path). this way laravel saves the file under storage/app/public directory.
after that, you can get the URL of the file according to this answer.
I figured it out thank you for your answer.
This is my code:
public function generatePDF()
{
$this->mailorder = Session::get('order');
$this->cart = Session::get('cart');
$data = [
'id' => $this->mailorder->id,
'client' => $this->mailorder->Contact,
'country' => $this->mailorder->country,
'city' => $this->mailorder->city,
'street' => $this->mailorder->street,
'postal' => $this->mailorder->postal,
'phone' => $this->mailorder->phone,
'email' => $this->mailorder->email,
'dateIn' => $this->mailorder->dateIn,
'dateOut' => $this->mailorder->dateOut,
'subtotal' => $this->mailorder->subtotal,
'tax' => $this->mailorder->tax,
'total' => $this->mailorder->total,
'cart' => $this->mailorder->cart,
'delivery' => $this->mailorder->delivery,
];
$filename = "order_{$this->mailorder->id}_{$this->mailorder->Contact}";
$path = storage_path('pdf/orders');
if(!File::exists($path)) {
File::makeDirectory($path, $mode = 0755, true, true);
}
else {}
$pdf = PDF::loadView('pdf.orderConfirmationPdf', $data)->save(''.$path.'/'.$filename.'.pdf');
;
return $pdf->download(''.$filename.'.pdf');
}

How to get excel header and title in Maatwebsite?

Excel::load($file->getRealPath())->get();
This returns only items, not header.
You can get file title with:
$file = Excel::load($file->getRealPath())
$file->getTitle();
You can also call getTitle() on individual sheets:
foreach ($file->get() as $sheet) {
echo $sheet->getTitle();
}
use Maatwebsite\Excel\Concerns\WithProperties;
class InvoicesExport implements WithProperties
{
public function properties(): array
{
return [
'creator' => 'Patrick Brouwers',
'lastModifiedBy' => 'Patrick Brouwers',
'title' => 'Invoices Export',
'description' => 'Latest Invoices',
'subject' => 'Invoices',
'keywords' => 'invoices,export,spreadsheet',
'category' => 'Invoices',
'manager' => 'Patrick Brouwers',
'company' => 'Maatwebsite',
];
}
}
try this

Extend Laravel package

I've searched around and couldn't find a definitive answer for this...
I have a package DevDojo Chatter and would like to extend it using my application. I understand I'd have to override the functions so that a composer update doesn't overwrite my changes.
How do I go about doing this?
UPDATE
public function store(Request $request)
{
$request->request->add(['body_content' => strip_tags($request->body)]);
$validator = Validator::make($request->all(), [
'title' => 'required|min:5|max:255',
'body_content' => 'required|min:10',
'chatter_category_id' => 'required',
]);
Event::fire(new ChatterBeforeNewDiscussion($request, $validator));
if (function_exists('chatter_before_new_discussion')) {
chatter_before_new_discussion($request, $validator);
}
if ($validator->fails()) {
return back()->withErrors($validator)->withInput();
}
$user_id = Auth::user()->id;
if (config('chatter.security.limit_time_between_posts')) {
if ($this->notEnoughTimeBetweenDiscussion()) {
$minute_copy = (config('chatter.security.time_between_posts') == 1) ? ' minute' : ' minutes';
$chatter_alert = [
'chatter_alert_type' => 'danger',
'chatter_alert' => 'In order to prevent spam, please allow at least '.config('chatter.security.time_between_posts').$minute_copy.' in between submitting content.',
];
return redirect('/'.config('chatter.routes.home'))->with($chatter_alert)->withInput();
}
}
// *** Let's gaurantee that we always have a generic slug *** //
$slug = str_slug($request->title, '-');
$discussion_exists = Models::discussion()->where('slug', '=', $slug)->first();
$incrementer = 1;
$new_slug = $slug;
while (isset($discussion_exists->id)) {
$new_slug = $slug.'-'.$incrementer;
$discussion_exists = Models::discussion()->where('slug', '=', $new_slug)->first();
$incrementer += 1;
}
if ($slug != $new_slug) {
$slug = $new_slug;
}
$new_discussion = [
'title' => $request->title,
'chatter_category_id' => $request->chatter_category_id,
'user_id' => $user_id,
'slug' => $slug,
'color' => $request->color,
];
$category = Models::category()->find($request->chatter_category_id);
if (!isset($category->slug)) {
$category = Models::category()->first();
}
$discussion = Models::discussion()->create($new_discussion);
$new_post = [
'chatter_discussion_id' => $discussion->id,
'user_id' => $user_id,
'body' => $request->body,
];
if (config('chatter.editor') == 'simplemde'):
$new_post['markdown'] = 1;
endif;
// add the user to automatically be notified when new posts are submitted
$discussion->users()->attach($user_id);
$post = Models::post()->create($new_post);
if ($post->id) {
Event::fire(new ChatterAfterNewDiscussion($request));
if (function_exists('chatter_after_new_discussion')) {
chatter_after_new_discussion($request);
}
if($discussion->status === 1) {
$chatter_alert = [
'chatter_alert_type' => 'success',
'chatter_alert' => 'Successfully created a new '.config('chatter.titles.discussion').'.',
];
return redirect('/'.config('chatter.routes.home').'/'.config('chatter.routes.discussion').'/'.$category->slug.'/'.$slug)->with($chatter_alert);
} else {
$chatter_alert = [
'chatter_alert_type' => 'info',
'chatter_alert' => 'You post has been submitted for approval.',
];
return redirect()->back()->with($chatter_alert);
}
} else {
$chatter_alert = [
'chatter_alert_type' => 'danger',
'chatter_alert' => 'Whoops :( There seems to be a problem creating your '.config('chatter.titles.discussion').'.',
];
return redirect('/'.config('chatter.routes.home').'/'.config('chatter.routes.discussion').'/'.$category->slug.'/'.$slug)->with($chatter_alert);
}
}
There's a store function within the vendor package that i'd like to modify/override. I want to be able to modify some of the function or perhaps part of it if needed. Please someone point me in the right direction.
If you mean modify class implementation in your application you can change the way class is resolved:
app()->bind(PackageClass:class, YourCustomClass::class);
and now you can create this custom class like so:
class YourCustomClass extends PackageClass
{
public function packageClassYouWantToChange()
{
// here you can modify behavior
}
}
I would advise you to read more about binding.
Of course a lot depends on how class is created, if it is created using new operator you might need to change multiple classes but if it's injected it should be enough to change this single class.

Resources