Jump to content

maxxd

Gurus
  • Posts

    1,655
  • Joined

  • Last visited

  • Days Won

    51

Posts posted by maxxd

  1. namespace Tests\Unit;
    use Tests\TestCase;
    class APITest extends TestCase
    {
       protected $db;
       const DB_URL = "https://sample.testing.edu/db.json";
       public function setUp(): void
       {
           parent::setUp();
           $this->db = json_decode(file_get_contents(self::DB_URL));
       }
       /**
        * The endpoint under test should return JSON of an array of objects containing users ids
        * and their total time
        * [
        *   {'user_id': <int>, 'seconds_logged': <int>},
        *   ... other users ...
        * ]
        *
        * @test
        */
       public function it_should_provide_sum_of_all_users_time()
       {
           $user = $this->db->users[array_rand($this->db->users)];
           $totalSecondsLogged = array_reduce($this->db->timelogs,
             function ($c, $i) use ($user) {
                 return $c + ($i->user_id == $user->id ? $i->seconds_logged : 0);
             }, 0);
           $response = $this->json('GET', '/user-timelogs');
           $response->assertJsonFragment([
             'user_id' => $user->id,
             'seconds_logged' => $totalSecondsLogged,
           ]);
       }
    }

    There's more to the file, obviously, but this is the test that's  bombing right now. Also, the $this->db stub file contains the same data I'm working with, so there's no issue there, and I think I've rebuilt my composer autoload file like nine or nineteen times, so I'm flat-out stumped. And tired. Mostly tired, but a good portion of that is due to the stumped, so...

  2. Hi y'all. First off, posting this here to hopefully avoid the noise that's happening in the Applications sub-forums, so mods please feel free to move if it's too inappropriate here.

    Anyway, I'm currently doing a skills assessment for a potential new job in Laravel - if I wasn't using Laravel I would've been done hours ago, but one of the requirements is Laravel. Honestly, for the most part I dig it - it's pretty simple, despite it's reliance on magic. Anyway, I've written a couple API routes and when I visit them in the browser everything works exactly as expected and desired. However, when I run the pre-built test file, I get a Symfony\Component\HttpKernel\Exception\NotFoundHttpException for /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php.

    The route as defined in api.php:

    use App\Http\Controllers\User;
    
    /**
     * I tried using a Resource Collection here - there's obviously something about those
     * that I'm missing, because it actively refused to do anything worthwhile. I'd pass in
     * UserModel::with('timelogs')->get() like I use in \App\Http\Controllers\User::getTotalSeconds(),
     * and it didn't care. Just printed out absolute garbage, no matter what I fed to it.
     */
    Route::get('/user-timelogs', function(Request $request) {
        $u = new User;
        return $u->getTotalSeconds();
    });

    And the controller code:

    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use App\User as UserModel;
    
    class User extends Controller
        public function getTotalSeconds()
        {
            $users = UserModel::with('timelogs')->get();
            $ret = [];
            foreach($users as $user){
                array_push($ret, [
                    'user_id' => $user->id,
                    'seconds_logged' => $this->calculateTime($user->timelogs)
                ]);
            };
            return json_encode($ret);
        }
    
        private function calculateTime($logs)
        {
            $totalTime = 0;
            foreach($logs as $log){
                $totalTime += $log->seconds_logged;
            }
            return $totalTime;
        }
    }

    The model file for good measure:

    namespace App;
    
    use Illuminate\Notifications\Notifiable;
    use Illuminate\Contracts\Auth\MustVerifyEmail;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    
    class User extends Authenticatable
    {
        use Notifiable;
    
        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
            'name', 'email', 'password', 'id',
        ];
    
        /**
         * The attributes that should be hidden for arrays.
         *
         * @var array
         */
        protected $hidden = [
            'password', 'remember_token',
        ];
    
        /**
         * The attributes that should be cast to native types.
         *
         * @var array
         */
        protected $casts = [
            'email_verified_at' => 'datetime',
        ];
    
        public function timelogs()
        {
            return $this->hasMany('App\Timelog');
        }
    }

    Again, when I visit localhost/api/user-timelogs, the user IDs and correct total of seconds is right there. It's just in the test file that it's an issue. Anybody have any ideas?

  3. I'm not saying it's not run right, I'm saying it's not run at all.

    You assign the SQL string to the variable $sql, then check if "0". If "0", you overwrite the value of $sql with a completely different string, which you then execute. If not "0" (will never happen), you print the word "Fail".

    Read out loud to yourself or someone else (preferably someone patient and understanding) each step of your code. If it helps, write it out in what's called 'psuedo-code' - prose versions of what the code is doing at each step of the process.

  4. 15 minutes ago, Kenny_Luck said:

    Im just learning the double prevention which im going to do for my assignment 

    OK. First thing I would recommend is to read the documentation.

    You don't mention if you're using PDO, mysqli, or another DB abstraction, but each has a different usage so it's important you read the documentation for the API you're using. Right now, you define a select query but don't actually run the query. You also have a conditional statement on what is effectively a non-existent comparison, so the logic is flawed.

    There are a lot of good resources out there, but they're sometimes buried under really bad resources. Ask here - someone will tell which you have. For instance, if you've quoted the full extent of your code here, I'd venture a guess that whatever source you're using to learn is not terribly good.

  5. 15 minutes ago, requinix said:

    You have a query there already. It returns a count. If you don't want a count and you want data instead then change the query to suit...

    The query is never actually run, though, so it technically doesn't return anything. It is an excellent example of SQL injection, though - or it would be if it was actually executed. Also, if("0") will - unless I'm mistaken - never be false.

    OP - is this for a class or did you get a project thrust upon you?

  6. 5 minutes ago, SaranacLake said:

    Sounds like you are talking about an eBook.  Even if I just use a file(s), there wouldn't be bookmarking built in automatically, right?  (Bookmarking is probably another reason some people get snobbish about eBooks.)

    You can add bookmarks to PDFs. It's in the left toolbar.

    6 minutes ago, SaranacLake said:

    What do you mean by "serialize"?

    Basically, break up into chunks. It's not an exact description of what you're proposing, but my brain's a bit fried by many things right now and it was the only word that came to mind.

    In all honesty, it sounds like it's a question of preference - kinda like storing images in a database using a blob. I'm not a fan of it personally, but some people are. Neither side is really right or wrong, just convicted.

    9 minutes ago, SaranacLake said:

    On a side note, one of the challenges when you are creating something that you've never done before is that you just don't know until you've built things and then can see if they are a good or not so good design.  But then that is why geeks like programming! 🙂

    Too true!

  7. It could absolutely work.

    For me, though, I'm not sure it'd be worth the extra overhead. After all, now you have to devise and code a way to track what page a user is on when she "closes" the book both when the user is and is not connected to the internet (the user could start reading at home, then continue in the car on a trip or something). And I know I always want bookmarks when reading technical docs, let alone highlights and whatnot.

    However, that's for me and my situation, which is obviously different than yours. I don't think you'll run into any major issues if you basically serialize your books into posts stored in a database, but as has been pointed out it's not really that great a boost to the security of the book itself. Could be a fun project to code, though 😁.

  8. Amazon offers an app that helps you to create an e-book from a Word document. My 70-year old dad has published and is now selling at least 2 e-books on Amazon right now using it. I can ask what exactly the name was if you don't feel like googling it yourself.

    If you're determined, however, I'd agree with pretty much everybody on this thread - put the files outside the webroot and serve them only after you run your account verification. If the user is determined to steal something off your website, there are so many ways to do it that no anti-theft practice is going to stop them. Sorry.

  9. On the off chance someone finds this in the future, apparently the answer is that you don't specify the auto-increment column and the call to $table->timestamps() must come last in the method. I finally dropped the $table->bigIncrement('id'); line and put the $table->timestamps(); call last in the stack, and now it works. So, you know... cool.

  10. Hi y'all.

    So I'm not new to frameworks in general but am new to Laravel specifically. I'm working through a thing and am running into an issue where a migration will create the specified table, but won't create the proper columns. Using the example in the documentation I get this behavior. For instance,

    <?php
    
    use Illuminate\Support\Facades\Schema;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;
    
    class CreateFlightsTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('flights', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('name');
                $table->string('airline');
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::drop('flights');
        }
    }

    This leaves me with a table named 'flights' that has the columns 'id', 'created_at', and 'updated_at'. Please note this code is copied and pasted from the Laravel migration documentation.

    Anybody have any words of wisdom on this? It's driving me nuts and I'm sure it's something simple I just don't know about.

  11. Drupal works on the idea of hooks - predefined actions that fire at certain times in the execution of the application and will run any functions or object methods that have been assigned to that hook. Think mini state-machine, kinda. See here for more information, and here for a list of native hooks. I haven't dug too much into Drupal, honestly (I looked into it as a WordPress replacement at my previous job, but decided the admin area would be too difficult for our clients to work with), but once I got the list of available hooks things got much, much easier to deal with.

    Like any framework or CMS, there's a lot of "magic" that happens. It's kind of a pain and a bit difficult at first because  - well yeah, you're absolutely right - a lot of it isn't terribly well documented if it's documented at all. However if you don't want to build the thing from scratch you're gonna have to deal with that. As far as I know, using a framework like Laravel or Symfony isn't going to be all that different with regard to this kind of thing - they're all dialects of PHP, and each has their own idiosyncrasies.

    Now that having been said, if what you've described is the full extent of what you're looking to do I'd be rather surprised if there weren't plugins available in the Drupal ecosystem that can do what you want without having to code at all. Maybe some custom JS or CSS just to personalize things but the heavy lifting should be taken care of out of the box.

  12. Honestly, given the light specs you've described I think a framework would probably do most of the work for you. If you're wanting to learn, do it from scratch - what you've described is not tough to do (it is, however, tough to do right - which makes it a good learning experience). If it's a work thing where you're on a deadline but you've got free reign, look at some frameworks. Heck, what you've described can be done in WordPress with little to no coding.

  13. It looks like your validation script makes zero sense, but it's hard to tell without braces and/or correct indentation. But it certainly looks like the first thing you do is attempt to assign $_POST['account'] to $acct_subject if and only if $_POST['account'] is empty.

  14. Your while() criteria is incorrect and unnecessary. I haven't tested this code, but give it a shot:

    $acceptedStates = [
    	'Feasibility',
    	'Measure Up',
    	'Model Drawing',
    	'Concept Design',
    	'Developed Design',
    	'Resource Consent',
    	'Construction Documentation',
    ];
    
    $xml = simplexml_load_string($response);
    $xml = usort($xml, function($a, $b){
    	return $a['job_due'] <=> $b['job_due'];
    });
    
    foreach($xml->Jobs->Job as $item) {
    
    	if(!in_array((string)$item->State, $acceptedStates)){
    		continue;
    	}
    
    	$projects[] = [
    			'job_no'          => (string)$item->ID,
    			'job_name'        => (string)$item->Name,
    			'job_due'         => date('d/m/Y', strtotime($item->DueDate)),
    			'job_status'      => (string)$item->State,
    			'job_staff'       => (string)$item->Assigned->Staff->Name,
    	];
    
    }

     

  15. All that having been said, if you're using $_POST input in a WordPress environment (which obviously I know you are), use some kind of safety features. I'd recommend at least using a WordPress nonce in the form output and data validation routines, and use the wpdb::prepare() method on the query. It's not a prepared statement exactly, but it is a little more responsible than just blindly trusting user-submitted data, especially if you're expanding your user base as you said you were in one of the other threads.

  16. 7 hours ago, ajoo said:

    I do have more questions, but seriously, I am a bit scared to ask them.

    Don't let my bad mood scare you off - most people around here are very helpful and nice.

    Having said that, one of the things that's going to help you learn how to code is to try things. The code you've already seen in this thread uses class-based selectors and dynamic ID and class assignment. So, if you extrapolate the two, you can use the dynamic class/ID assignment you've seen with the appropriate selector method. If you try it and it doesn't work out, then post the code you've tried and we can help you figure out why it didn't work; the important part is to show the work you've done.

  17. 5 hours ago, ajoo said:

    I hope this is the right way to go about it.

    It's not.

    5 hours ago, ajoo said:

    If there is a better simpler way, please suggest.

    Here.

    5 hours ago, ajoo said:

    Could I have done it using say the class property or the name of the input field instead of using tabIndex?

    Yes.

    5 hours ago, ajoo said:

    If so, then can you kindly demonstrate how it could be done by that method. 

    Here.

    Admittedly, I'm asking you to think a little when it comes to some of it, but ... really? Beyond that, Barand has been his typical self and gone above and beyond the call of duty to answer your questions in no uncertain terms and with concrete code examples; yet there are more requests to simply do it for you.

    • Like 1
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.